[Answered ]-Automatic Image resizing for every uploaded images by users

1👍

Here’s a working example based on my comment:

/**
 * Resize a base 64 Image
 * @param {String} base64 - The base64 string (must include MIME type)
 * @param {Number} newWidth - The width of the image in pixels
 * @param {Number} newHeight - The height of the image in pixels
 */

const toBase64 = file => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => resolve(reader.result);
  reader.onerror = error => reject(error);
});

async function Main() {
  const file = document.querySelector('.file').files[0];
  const newFile = await toBase64(file);

  document.body.append("Before: ");
  let before = document.createElement("img");
  before.src = newFile;
  document.body.appendChild(before);

  resizeBase64Img(newFile, 200, 200).then(resized => {
    let img = document.createElement("img");
    img.src = resized;
    document.body.appendChild(img);
  });
}

function resizeBase64Img(base64, newWidth, newHeight) {
  return new Promise((resolve, reject) => {
    var canvas = document.createElement("canvas");
    canvas.style.width = newWidth.toString() + "px";
    canvas.style.height = newHeight.toString() + "px";
    let context = canvas.getContext("2d");
    let img = document.createElement("img");
    img.src = base64;
    img.onload = function() {
      context.scale(newWidth / img.width, newHeight / img.height);
      context.drawImage(img, 0, 0);
      resolve(canvas.toDataURL());
    }
  });
}

document.querySelector(".file").addEventListener("input", Main);
<input class="file" type="file">

0👍

Leave a comment