I'm trying to rotate photos based on their original rotation, as set by the camera in EXIF image data. The trick is that all this should happen in the browser, using JavaScript and HTML5 "canvas".
Currently I'm able to get the rotation of the image but can't rotate the image in case it is inverted or flipped.
JS code..
function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
}
canvasCtx = document.getElementById("panel").getContext("2d");
document.getElementById("ifile").onchange = function(event) {
getOrientation(document.getElementById("ifile").files[0], function(orientation) {
alert('orientation: ' + orientation);
});
this.imageFile = event.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
//img.style.width = "300px";
//img.style.height = "300px";
img.onload = function() {
drawImage(img);
}
img.src = event.target.result;
}
reader.readAsDataURL(this.imageFile);
}
drawImage = function(img) {
this.canvasCtx.canvas.width = 300;//img.width;
this.canvasCtx.canvas.height = 300;//img.height;
if(img.width>img.height){ //Landscape Image
canvasCtx.width = 300;
canvasCtx.height = 300 / img.width * img.height;
} else { //Portrait Image
canvasCtx.width = 300 / img.height * img.width;
canvasCtx.height = 300;
}
canvasCtx.translate(img.width * 0.5, img.height * 0.5);
/// rotate canvas context
canvasCtx.rotate(0.5 * Math.PI); /// 90deg clock-wise
/// translate back so next draw op happens in upper left corner
canvasCtx.translate(-img.width * 0.5, -img.height * 0.5);
this.canvasCtx.drawImage(img,0,0,canvasCtx.width, canvasCtx.height);
url = canvasCtx.canvas.toDataURL();
}
I have 2 photos taken form ios, android having orientation as 3 and 6 respectively. I would like to change their orientation to 1. Can't figure how to do that.Please help..