So I am made an image upload form that takes an image and adds an overlay. The issue is that if an image is uploaded via an iPhone or Android phone, the image is usually incorrectly rotated because of the EXIF data. I have found a way to map the orientation to a number (1-10), but the code I found online to rotate the canvas doesn't seem to be working. Any help would be appreciated.
JS
function showimagepreview(input, ori) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
ratio = img.height / img.width,
maxRatio = 0.6666666666666667;
var width = img.width,
height = img.height;
// transform context before drawing image
switch (ori) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height ); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height ); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height , 0); break;
case 7: ctx.transform(0, -1, -1, 0, height , width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: ctx.transform(1, 0, 0, 1, 0, 0);
}
canvas.width = 640;
canvas.height = 640;
drawImageProp(ctx, img, 0, 0, canvas.width, canvas.height); // Centers BG image (similar to background-position: cover)
var img2 = new Image();
img2.onload = function() {
ctx.drawImage(img2, 0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/png'),
preview = document.getElementById('img-preview'),
$img = $('<img id="new-img" src="' + data + '" />'),
$downloadImg = $('#download-img'),
$shareImg = $('#share-img');
$img.css({'border-radius': '6px'})
preview.innerHTML = '';
$img.hide().appendTo(preview).fadeIn(500);
$downloadImg.hide().appendTo(preview).fadeIn(500);
$shareImg.hide().appendTo(preview).fadeIn(500);
$.ajax({
type: "POST",
url: "http://data-uri-to-img-url.herokuapp.com/images.json",
data: {
"image[data_uri]": data.split(',')[1] // ".split(',')[1]" Safely removes Base64 prefix for POST
}
}).done(function(response) {
var url = response['url'],
fbUrl = "https://www.facebook.com/sharer/sharer.php?u=" + url;
$shareImg.find('a').attr('href', fbUrl);
console.log(url);
});
};
img2.src = "http://i.imgur.com/xNpwbZj.png"
}
img.src = e.target.result;
}
filerdr.readAsDataURL(input.files[0]);
}
}