Base64 Thumbnail Generator

Takes and returns base64. Crops to centered square & shrinks to desired size.

by Sebastian Kay

HTML

<h3>Base64 source image</h3>
<img id="source-image"...

JavaScript

function thumbnailify(base64Image, targetSize, callback) {
  var img = new Image();

  img.onload = function() {
    var width = img.width,
        height = img.height,
        canvas = document.createElement('canvas'),
        ctx = canvas.getContext("2d");

    canvas.width = canvas.height = targetSize;

    ctx.drawImage(
      img,
      width > height ? (width - height) / 2 : 0,
      height > width ? (height - width) / 2 : 0,
      width > height ? height : width,
      width > height ? height : width,
      0, 0,
      targetSize, targetSize
    );

    callback(canvas.toDataURL());
  };

  img.src = base64Image;
};

var sourceImage = document.getElementById("source-image"),
		thumbnail = document.getElementById("thumbnail");

thumbnailify(sourceImage.src, 100, function(base64Thumbnail) {
	thumbnail.src = base64Thumbnail;
});