Skip to content

Instantly share code, notes, and snippets.

@bradgorman
Forked from codeincontext/gist:3862543
Created December 9, 2012 21:02
Show Gist options
  • Save bradgorman/4247000 to your computer and use it in GitHub Desktop.
Save bradgorman/4247000 to your computer and use it in GitHub Desktop.

Revisions

  1. bradgorman revised this gist Dec 9, 2012. No changes.
  2. @codeincontext codeincontext created this gist Oct 10, 2012.
    76 changes: 76 additions & 0 deletions gistfile1.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    <!DOCTYPE html>
    <html>
    <head>
    <title>iOS6 Safari Photo Capture Demo</title>

    <script type="text/javascript">
    window.onload = function() {
    var input = document.getElementById("input");
    input.addEventListener("change", handleFile);
    }

    function handleFile(e) {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext("2d");

    var reader = new FileReader;
    reader.onload = function (event) {
    var img = new Image();
    img.src = reader.result;
    img.onload = function () {
    canvas.width = img.width/3;
    canvas.height = img.height/3;

    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);

    // Do whatever image operation you need (resize/crop, visual effects, barcode detection, etc.+
    invertImage(ctx, canvas);

    // You can even upload the new image to your server
    // postCanvasDataToServer(canvas);
    }
    }
    reader.readAsDataURL(e.target.files[0]);
    }

    // Just an example of the pixel-by-pixel manipulations you could make on the client side
    function invertImage(ctx, canvas) {
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var data = imageData.data;

    for (var i = 0; i < data.length; i += 4) {
    data[i] = 255 - data[i]; // red
    data[i + 1] = 255 - data[i + 1]; // green
    data[i + 2] = 255 - data[i + 2]; // blue
    // i+3 is alpha
    }

    ctx.putImageData(imageData, 0, 0);
    }


    // An example of how you would post the image on the canvas to a server
    function postCanvasDataToServer(canvas) {
    var finalFile = canvas.toDataURL("image/png");

    var postData = 'canvasData=' + finalFile;
    var ajax = new XMLHttpRequest();
    ajax.open('POST', 'upload_image', true);
    ajax.setRequestHeader('Content-Type', 'canvas/upload');

    ajax.onreadystatechange = function () {
    if (ajax.readyState == 4) {
    alert('posted');
    }
    }
    ajax.send(postData);
    }
    </script>
    </head>
    <body>
    <h1>iOS6 Safari Photo Capture Demo</h1>
    <input type="file" id="input" name="input" accept="image/*"></input>
    <canvas id="canvas"></canvas>

    </body>
    </html>