I have a functionality in a web app that opens up a Bootstrap modal window on uploading a profile picture. It allows the user to crop and finalize the profile display.
I found out that sometimes the orientation of photos can be messed up. I added a few parts to check the EXIF orientation data of the images and rotate and fix them accordingly. Now even though it looks like the logic is right, I can't wrap my head around the context and canvas concept of HTML 5 because the end result quite obviously shows I'm missing something.
Here is the modal load handler:
$("#imageJcrop").on ("shown.bs.modal", function(e) {
var img = new Image();
img.onload = function(){
var canvas = document.createElement("canvas");
canvas.height = img.height;
canvas.width = img.width;
var ctx = canvas.getContext("2d");
ctx.translate(canvas.width/2, canvas.height/2);
//..check orientation data, this code assumes the case where its oriented 90 degrees off
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0, 0);
$(".editPhoto").attr("src", canvas.toDataURL("image/jpeg"));
$('<img id="cropbox" class="img-responsive" exif="true" src="' + canvas.toDataURL("image/jpeg") + '">').load(function() {
spinner.stop();
$(this).appendTo($("#imageJcrop .modal-body #cropbox-container"));
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 300, 300],
aspectRatio: 1,
bgColor: 'white'
});
});
}; });
(I can't post the images so I'm pasting the imgur links here)
The actual image without the above code being applied: http://i.imgur.com/jffkaUu.png
After applying the HTML5 canvas and context transformation http://i.imgur.com/D9qQKHZ.png
Where am I going wrong with this?