Little demo by @codepo8 which reads the thumbnail out of the EXIF data of an image:
The code itself is very simple: it opens a FileReader
and seeks for the second occurrence (*) of 0xFF 0xD8
(Start of Image) along with its following 0xFF 0xD9
(End of Image). All bytes in between are the thumbnail image.
function getThumbnail(file) {
if (file.type === "image/jpeg") {
var reader = new FileReader();
reader.onload = function (e) {
var array = new Uint8Array(e.target.result), start, end;
for (var i = 2; i < array.length; i++) {
if (array[i] === 0xFF) {
if (!start) {
if (array[i + 1] === 0xD8) {
start = i;
}
} else {
if (array[i + 1] === 0xD9) {
end = i;
break;
}
}
}
}
if (start && end) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(new Blob([array.subarray(start, end)], {type:"image/jpeg"}));
var imgf = new Image();
imgf.src = imageUrl;
document.body.appendChild(imgf);
}
};
reader.readAsArrayBuffer(file.slice(0, 50000));
}
}
(*) The second occurrence is used as all JPEG files start with 0xFF 0xD8
. However, to be technically correct – as more occurrences of 0xFF 0xD8
may be present – the code should first look for 0XFF 0xE1
which denotes the start of the EXIF Segment. It is in that segment that the thumbnail can be found. See this document for more info.
Leave a comment