<!DOCTYPE html>
<html>
<body>
<p>Image:</p>
<img id="forest" width="220" height="277" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190809013546/gfg_350X350.png"
alt="Forest">
<p>Canvas:</p>
<canvas id="Canvas" width="300" height="200"
style="border:15px solid #000066;">
Your browser not support the HTML5 canvas .
</canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("Canvas");
var context = canvas.getContext("2d");
var img = document.getElementById("forest");
context.drawImage(img, 12, 8);
};
</script>
</body>
</html>
// 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
);
});
}