I was looking here for a method to orientate images client side using javascript.
I found something and finally got this script.
It seems the image is being passed correctly but then the result of ctx.drawImage(img, 0, 0);
is undefined and I don't get why.
I just need the function to return the new image as base64 so that I can handle properly for inserting in the dom. I am not sure I am returning it correctly either but there's a prior problem where as stated drawImage is returning undefined, it seems like it is trying a route undefined:1 GET http://myproject.dev/model/undefined 404 (Not Found)
probably I'm missing something stupid.
the event part
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
var base64img = this.result;
var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(this.result));
var srcOrientation = exif.Orientation;
var img = resetOrientation(base64img, srcOrientation);
$('#imagePreview').show().html('<img id="theImage" src="' + img + '" class="img-fluid" alt="Your Image" />');
}
}
})
});
The function that takes care of orientation
function resetOrientation(srcBase64, srcOrientation) {
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
console.log(ctx);
// set proper canvas dimensions before transform & export
if ([5,6,7,8].indexOf(srcOrientation) > -1) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
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);
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
return img;
};
img.src = srcBase64;
};
The function to convert base64 to array for EXIF checking.
function base64ToArrayBuffer (base64) {
base64 = base64.replace(/^data:([^;]+);base64,/gmi, '');
var binaryString = window.atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}