Read EXIF thumbnail from JPG image using JavaScript

Little demo by @codepo8 which reads the thumbnail out of the EXIF data of an image:

exifthumbnail

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.

Demo →
Source →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.