I am using jQuery to append an image to a div
, while setting the image's source to a local image the user selects. Everything works great, except that the image appears upside-down or sideways sometimes, depending on the image (as far as I know, randomly). The jQuery looks like this:
$('<div class="image_preview">\
<img src="' + URL.createObjectURL(file) + '" />\
</div> ').hide().prependTo($preview_div).fadeIn("fast");
The file
object is simply a file taken from a file input element.
The image preview div has some css that looks like:
.image_preview img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
max-width: 95%;
max-height: 95%;
}
After searching countless threads I can't find anything on this topic other than people suggesting "maybe the image is supposed to be that way". I verified these images are actually being flipped when rendered. If anyone has heard of such a thing and can even point me in the right direction I would greatly appreciate it. Thanks.
The photos are likely being presenting in their natural orientation. When taking a photograph, a bunch of meta data about the camera is stored in something called EXIF data, things such as time, location, shutter, and orientation.
Most photo viewing software, including the ones on the device itself, take the orientation into account and display it accordingly. As a result, your logic will need to do the same.
The following StackOverflow post describes in further detail how to accomplish this in JavaScript: extract exif orientation data from image
var b64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABA......";
var bin = atob( b64.split( ',' )[1] ); // convert base64 encoding to binary
var exif = EXIF.readFromBinaryFile( new BinaryFile( bin ) );
console.log( exif.orientation );
For more information on the FileReader API and the readFromBinaryFile
method, here is a link to the MDN: https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsBinaryString