Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

JavaScript resize image

// This function get image files from input and resize it with specific dimension and quality
export async function resizeImage(inputImgFiles, maxWidth, maxHeight, quality) {
  const imgFilesArray = Object.values(inputImgFiles).filter(checkExtension);
  const promises = imgFilesArray.map(async (imgFile) => {
    const readerResult = await fileReader(imgFile);
    const resizedImage = await resizeImageToBlob(readerResult, maxWidth, maxHeight, quality);
    return resizedImage;
  });
  const resizedImagesArray = await Promise.all(promises);
  return resizedImagesArray;
}

// Check input files extension
export function checkExtension(file) {
  file = file.name.toLowerCase();
  const extension = file.substr(file.lastIndexOf(".") + 1);
  if (extension === "jpg" || extension === "jpeg" || extension === "png") {
    return true;
  } else {
    return false;
  }
}

// read image file
export function fileReader(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      const img = document.createElement("img");
      img.onload = () => {
        resolve(img);
      };
      img.src = event.target.result;
    };
    reader.readAsDataURL(file);
  });
}

// resize and return data URI and blob file
export function resizeImageToBlob(img, maxWidth, maxHeight, quality) {
  return new Promise((resolve) => {
    const canvas = document.createElement("canvas");
    let width = img.width;
    let height = img.height;

    if (width > height) {
      if (width > maxWidth) {
        height = Math.round((height *= maxWidth / width));
        width = maxWidth;
      }
    } else if (height > maxHeight) {
      width = Math.round((width *= maxHeight / height));
      height = maxHeight;
    }

    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);

    canvas.toBlob(
      (blob) => {
        resolve([canvas.toDataURL("image/jpeg", quality), blob]);
      },
      "image/jpeg",
      quality
    );
  });
}
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #JavaScript #resize #image
ADD COMMENT
Topic
Name
4+7 =