On my website, I let users upload multiple images at a time. I'd like to check the EXIF rotation tag of each uploaded image to manually rotate the image in the browser if necessary.
I found the following response for reading the EXIF rotation value for an image:
https://stackoverflow.com/a/7585267/1720985
This works for me when I upload a single image, but it doesn't work when I try to upload multiple images because fr.onloadend finishes after all images have already been read.
My current strategy is to save the corresponding image names and rotation values into a hash (rotate_images) and use this hash later to apply the rotation to the rendered images on the page.
This is currently what I have:
$('#file').change(function(){
for(var i = 0; i<this.files.length; i++){
var file = this.files[i];
var file_path = this.files.item(i).name;
if(file_path){
var startIndex = (file_path.indexOf('\\') >= 0 ? file_path.lastIndexOf('\\') : file_path.lastIndexOf('/'));
var filename = file_path.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
console.log('uploading image ' + filename);
}
fr = new FileReader;
fr.onloadend = function(){
console.log('getting exif');
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
var orientation = exif.Orientation;
console.log(filename +' has orientation ' + orientation);
if(orientation != 1){
rotate_images[filename] = orientation;
}
}
fr.readAsBinaryString(file);
}
});
When I look at the logs, I get the following:
uploading image camera.JPG
uploading image robot.JPG
uploading image snack.jpg
getting exif
snack.jpg has orientation 8
getting exif
snack.jpg has orientation 8
getting exif
snack.jpg has orientation 1
You can see from the logs that it's reading the last file. How can I delay my for loop until after each file is read? Or is there another way to read EXIF orientation information from multiple files?
Here are the scripts I'm using for reading the EXIF information: