Skip to content

Instantly share code, notes, and snippets.

@sungchuni
Last active January 19, 2021 07:30
Show Gist options
  • Save sungchuni/123eda583c57408d94a4afbc189cc171 to your computer and use it in GitHub Desktop.
Save sungchuni/123eda583c57408d94a4afbc189cc171 to your computer and use it in GitHub Desktop.
async function parseOrientation(blob) {
const APP1_MARKER = 0xffe1;
const EXIF_HEADER = Array.from("Exif")
.map((c) => c.charCodeAt())
.reverse()
.reduce(
(accumulator, charCode, index) =>
accumulator + charCode * 16 ** (index * 2)
);
const INTEL_BYTE_ALIGN = 0x4949;
const ORIENTATION_TAG_NO = 0x0112;
const orientation = {
value: 9,
valueOf() {
return this.value;
},
title: undefined,
toString() {
return this.title;
},
};
const arrayBuffer = await getArrayBuffer(blob);
const dataView = {
exif: null,
whole: new DataView(arrayBuffer),
};
for (let i = 0; i < dataView.whole.byteLength - 4; i++) {
if (
dataView.whole.getUint16(i) === APP1_MARKER &&
dataView.whole.getUint32(i + 4) === EXIF_HEADER
) {
const size = dataView.whole.getUint16(i + 2);
dataView.exif = new DataView(arrayBuffer.slice(i, size));
break;
}
}
if (dataView.exif === null) {
return orientation;
}
const littleEndian = dataView.exif.getUint16(10) === INTEL_BYTE_ALIGN;
for (let i = 0; i < dataView.exif.byteLength - 2; i = i + 2) {
if (dataView.exif.getUint16(i, littleEndian) === ORIENTATION_TAG_NO) {
const value = dataView.exif.getUint16(i + 8, littleEndian);
const title =
(value === 1 && "upper left") ||
(value === 3 && "lower right") ||
(value === 6 && "upper right") ||
(value === 8 && "lower left") ||
undefined;
Object.assign(orientation, {value, title});
break;
}
}
return orientation;
}
function getArrayBuffer(blob) {
if ('arrayBuffer' in blob) {
return blob.arrayBuffer()
} else {
return new Promise(resolve => {
const fileReader = new FileReader()
fileReader.readAsArrayBuffer(blob)
fileReader.onloadend = ({ target: { result } }) => resolve(result)
})
}
}
@sungchuni
Copy link
Author

sungchuni commented Jul 30, 2020

😤 Parse blob to extract only orientation and stop parsing.
refer to https://www.media.mit.edu/pia/Research/deepview/exif.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment