Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating thumbnail squares of images in javascript (without losing aspect ratio)

I am making a client side Drag and Drop file upload script as a bookmarklet. Before uploading I am using the File API to read the images into base64 format and display them as thumbnails.

This is how my thumbnails look like. I want them to look more square but without loosing their aspect ratio. (please ignore progress bar) wide thumbnails

This is how I want the thumbnails to be like, they are centered and being cropped based on min(height,width). square thumbnails

Can I do this using javascript only (changing styles via script will do)? Please try to make sure that your solution will fit with base64 images (after the images are read via file API as DATA URL).

I have uploaded these exact set of images here.

Thanks for the help.

like image 881
bits Avatar asked Feb 23 '23 19:02

bits


1 Answers

Just wanted to share how I resolved my issue. Since I wanted a purely javascript only solution, I used throwaway canvas elements to do the dirty work.

Here is my code for the same:

function resizeImage(url, width, height, callback, file) {
  console.log("In_resizeImage");
  var sourceImage = new Image();

  sourceImage.onload = (function (f) {
      return function (evt) {
        console.log("In_sourceImage_onload");
        console.log("sourceImage.width:" + sourceImage.width);
        console.log("sourceImage.height:" + sourceImage.height);
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;

        if (sourceImage.width == sourceImage.height) {
          canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
        } else {
          minVal = Math.min(sourceImage.width, sourceImage.height);
          if (sourceImage.width > sourceImage.height) {
            canvas.getContext("2d").drawImage(sourceImage, (sourceImage.width - minVal) / 2, 0, minVal, minVal, 0, 0, width, height);
          } else {
            canvas.getContext("2d").drawImage(sourceImage, 0, (sourceImage.height - minVal) / 2, minVal, minVal, 0, 0, width, height);
          }
        }
        callback(canvas.toDataURL(), f);
      }
    })(file);

  sourceImage.src = url;
}

I was directly dealing with image files so I was able to use Image object. For others to use, little bit tweaking might be required.

like image 52
bits Avatar answered Mar 09 '23 01:03

bits