src/methods.js
function shrinkImage(base64Image, targetSize) {

  return new Promise( (resolve, reject) => {

    let canvas  = document.createElement('canvas');
    let image   = new Image();

    image.onload = _ => {

      canvas.height = image.naturalHeight;
      canvas.width  = image.naturalWidth;

      canvas.getContext('2d').drawImage(image, 0, 0);

      return resolve(shrink(95));

      function shrink(quality) {
        let redrawnImage = canvas.toDataURL('image/jpeg', quality/100);

        // 1. Stop at zero because quality can't get any worse!
        // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob.
        return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage;
      }

    };

    image.src = base64Image;

  });
}
function shrinkImage(base64Image, targetSize) {

  return new Promise( (resolve, reject) => {

    let canvas  = document.createElement('canvas');
    let image   = new Image();

    image.onload = _ => {

      canvas.height = image.naturalHeight;
      canvas.width  = image.naturalWidth;

      canvas.getContext('2d').drawImage(image, 0, 0);

      return resolve(shrink(95));

      function shrink(quality) {
        let redrawnImage = canvas.toDataURL('image/jpeg', quality/100);

        // 1. Stop at zero because quality can't get any worse!
        // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob.
        return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage;
      }

    };

    image.src = base64Image;

  });
}
function shrinkImage ( base64Image , targetSize ) { return new Promise ( ( resolve , reject ) => { let canvas = document . createElement ( 'canvas' ) ; let image = new Image ( ) ; image . onload = _ => { canvas . height = image . naturalHeight ; canvas . width = image . naturalWidth ; canvas . getContext ( '2d' ) . drawImage ( image , 0 , 0 ) ; return resolve ( shrink ( 95 ) ) ; function shrink ( quality ) { let redrawnImage = canvas . toDataURL ( 'image/jpeg' , quality / 100 ) ; // 1. Stop at zero because quality can't get any worse! // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob. return quality !== 0 && redrawnImage . length / 1.33 > targetSize ? shrink ( quality - 5 ) : redrawnImage ; } } ; image . src = base64Image ; } ) ; }
Rewrites base64 image using canvas until it is down to desired file size.
@param {string} base64Image Base64 image string.
@param {number} targetSize Desired file size in bytes.
@returns {string} Base64 string of resized image.
Rewrites base64 image using canvas until it is down to desired file size .