Skip to content

Instantly share code, notes, and snippets.

@navix
Last active July 20, 2019 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/78aaf98abc6365f86fb7a62b1a2a0a32 to your computer and use it in GitHub Desktop.
Save navix/78aaf98abc6365f86fb7a62b1a2a0a32 to your computer and use it in GitHub Desktop.
Image resizing in browser

Image resizing in browser

Resize image using canvas:

function resizeImage (src, resultWidth, resultHeight): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    let canvas = document.createElement('canvas');
    let img = document.createElement('img');
    img.onload = function () {
      let imageWidth = img.width;
      let imageHeight = img.height;
      let imageCoef = imageWidth / imageHeight;
      let resultCoef = resultWidth / resultHeight;

      let sx = 0;
      let sy = 0;
      let swidth = imageWidth;
      let sheight = imageHeight;
      if (resultCoef < imageCoef) {
        swidth = sheight * resultCoef;
        sx = (imageWidth - swidth) / 2;
      }
      else {
        sheight = swidth / resultCoef;
        sy = (imageHeight - sheight) / 2;
      }

      canvas.width = resultWidth;
      canvas.height = resultHeight;
      let ctx = canvas.getContext("2d");
      ctx.drawImage(img, sx, sy, swidth, sheight, 0, 0, resultWidth, resultHeight);

      resolve(canvas.toDataURL("image/png"));
    };
    img.src = src;
  });
}

Multi-resizing for anti-aliasing:

function pickPicture(event) {
  var reader = new FileReader();
  reader.onload = (e: any) => {
    resizeImage(e.target.result, 300, 300).then(pictureData => {
      resizeImage(pictureData, 150, 150).then(pictureData => {
        console.log('resized picture', pictureData);
      });
    });
  };
  reader.readAsDataURL(event.target.files[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment