I am trying to detect the EXIF data (Orientation) of an image and show it without being rotated when selected. For the image preview the FileReader API is being used. I was able to fix server side orientation but for frontend I have having trouble.
I am using this library to get the EXIF data of an image.
I have imported the exif.js
to my project.
<script src="frontend/js/exif.js">
HTML
<input id="choose-img" accept="image/*" name="image" type="file" onchange="readURLimg(this);">
<img class="img-uploaded" id="img-file">
jQuery
function readURLimg(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
/* Check Exif and fix orientation of image */
EXIF.getData([0], function() {
console.log('Exif=', EXIF.getTag(this, "Orientation"));
switch(parseInt(EXIF.getTag(this, "Orientation"))) {
case 2:
$img.addClass('flip'); break;
case 3:
$img.addClass('rotate-180'); break;
case 4:
$img.addClass('flip-and-rotate-180'); break;
case 5:
$img.addClass('flip-and-rotate-270'); break;
case 6:
$img.addClass('rotate-90'); break;
case 7:
$img.addClass('flip-and-rotate-90'); break;
case 8:
$img.addClass('rotate-270'); break;
}
});
$('#img-file').attr('src', e.target.result).width('50%').height('auto');
reader.readAsDataURL(input.files[0]);
}
}
In my console I am getting this error:
Uncaught ReferenceError: EXIF is not defined at FileReader.reader.onload
Any Suggestions?
Does this work?
function readURLimg(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = $('#img-file')
img.attr('src', e.target.result).width('50%').height('auto');
fixExifOrientation(img)
}
reader.readAsDataURL(input.files[0]);
}
}
function fixExifOrientation($img) {
$img.on('load', function() {
EXIF.getData($img[0], function() {
console.log('Exif=', EXIF.getTag(this, "Orientation"));
switch(parseInt(EXIF.getTag(this, "Orientation"))) {
case 2:
$img.addClass('flip'); break;
case 3:
$img.addClass('rotate-180'); break;
case 4:
$img.addClass('flip-and-rotate-180'); break;
case 5:
$img.addClass('flip-and-rotate-270'); break;
case 6:
$img.addClass('rotate-90'); break;
case 7:
$img.addClass('flip-and-rotate-90'); break;
case 8:
$img.addClass('rotate-270'); break;
}
});
});
}