Skip to content

Instantly share code, notes, and snippets.

@carlosmcevilly
Forked from codeincontext/gist:3862543
Created October 10, 2012 14:30
Show Gist options
  • Save carlosmcevilly/3865987 to your computer and use it in GitHub Desktop.
Save carlosmcevilly/3865987 to your computer and use it in GitHub Desktop.
Photo capture, manipulation, and upload in iOS6 Safari
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment