Compress Image in JS
How to compress image in JavaScript?

Jay Kumar is a proficient JavaScript and Node.js developer with 7 years of experience in building dynamic and scalable web applications. With a deep understanding of modern web technologies, Jay excels at creating efficient and innovative solutions. He enjoys sharing his knowledge through blogging, helping fellow developers stay updated with the latest trends and best practices in the industry.
You can compress image by using this method.
function compressImage(imageUrl) {
let image = new Image();
image.onload = () => {
let canvas = document.createElement('canvas');
let maxSize = 1504; // Define Size of Image
let width = image.width;
let height = image.height;
if (width > height && width > maxSize) {
height *= maxSize / width;
width = maxSize;
} else if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
let base64Image = canvas.toDataURL('image/jpeg').split(",")[1];
}
image.src = imageUrl;
}






