Skip to content

Instantly share code, notes, and snippets.

@KillerCodeMonkey
Created June 28, 2019 05:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KillerCodeMonkey/587b0c92d4578bb99c0ab0a15a79064b to your computer and use it in GitHub Desktop.
Save KillerCodeMonkey/587b0c92d4578bb99c0ab0a15a79064b to your computer and use it in GitHub Desktop.
JS script to detect jpeg orientation from exif data using filereader api
var orientation = function (file, callback) {
var fileReader = new FileReader();
fileReader.onloadend = function () {
var base64img = "data:" + file.type + ";base64," + _arrayBufferToBase64(fileReader.result);
var scanner = new DataView(fileReader.result);
var idx = 0;
var value = 1; // Non-rotated is the default
if (fileReader.result.length < 2 || scanner.getUint16(idx) != 0xFFD8) {
// Not a JPEG
if (callback) {
callback(base64img, value);
}
return;
}
idx += 2;
var maxBytes = scanner.byteLength;
var littleEndian = false;
while (idx < maxBytes - 2) {
var uint16 = scanner.getUint16(idx, littleEndian);
idx += 2;
switch (uint16) {
case 0xFFE1: // Start of EXIF
var endianNess = scanner.getUint16(idx + 8);
// II (0x4949) Indicates Intel format - Little Endian
// MM (0x4D4D) Indicates Motorola format - Big Endian
if (endianNess === 0x4949) {
littleEndian = true;
}
var exifLength = scanner.getUint16(idx, littleEndian);
maxBytes = exifLength - idx;
idx += 2;
break;
case 0x0112: // Orientation tag
// Read the value, its 6 bytes further out
// See page 102 at the following URL
// http://www.kodak.com/global/plugins/acrobat/en/service/digCam/exifStandard2.pdf
value = scanner.getUint16(idx + 6, littleEndian);
maxBytes = 0; // Stop scanning
break;
}
}
if (callback) {
callback(base64img, value);
}
}
fileReader.readAsArrayBuffer(file);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment