To reduce the file size of an image in JavaScript, you can use the HTML5 canvas element. The process involves creating a new canvas, drawing the image on it, resizing it, and then converting it to a compressed format like JPEG, PNG or WebP. Here is an example code snippet that demonstrates how to compress and reduce the size of an image in JavaScript using HTML5 canvas.
index.tsx638 chars24 lines
This function takes in a source image URL and quality (0 to 100) as input parameters. The quality value defines the level of compression, with 0 being the lowest and 100 being the highest. You can adjust the quality value to balance between image size and image quality.
To compress an image file on the server side, Node.js provides an image compression library such as sharp
or imagemin
.
gistlibby LogSnag