reduze the file size of a image in javascript

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.tsx
function compressImage(source, quality) {
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");

  // Load the image in canvas
  var img = new Image();
  img.src = source;

  // Wait for the image to load
  img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;

    // Draw image on the canvas
    ctx.drawImage(img, 0, 0, img.width, img.height);

    // Get the base64 encoded image data
    var dataURL = canvas.toDataURL("image/jpeg", quality/100);

    // Do something with the image (upload to server or display)
    console.log('Compressed Image:', dataURL);
  };
}
638 chars
24 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