41
loading...
This website collects cookies to deliver better user experience
/**
* CDraw a Canvas and resize the image.
* @param {object} image - Image Object
* @param {number} limitWidth - Max width
* @param {number} limitHeight - Max height
* @returns {string} - base64
*/
export default async function resizeImage(image, limitWidth, limitHeight) {
const aspect = image.width / image.height;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let canvasWidth;
let canvasHeight;
if (image.width > limitWidth || image.height > limitHeight) {
// If the image is larger than the specified size
if (aspect > 1) {
// For horizontal images
canvasWidth = limitWidth;
canvasHeight = limitHeight * (image.height / image.width);
} else {
// For portrait images
canvasWidth = limitWidth * (image.width / image.height);
canvasHeight = limitHeight;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
} else {
// Within the specified size
canvas.width = image.width;
canvas.height = image.height;
canvasWidth = image.width;
canvasHeight = image.height;
}
ctx.drawImage(
image,
0,
0,
image.width,
image.height,
0,
0,
canvasWidth,
canvasHeight
);
return canvas.toDataURL("image/jpeg", 0.85);
}
41