Compression function for compressing images uploaded to the web with React

Tiempo de lectura: < 1 minuto

You will be sharing a function today that helps us compress images we upload to our website using an input.

Dog in the Snow - pexels

Código:

html

const compressImage = (img: HTMLImageElement, maxWidth = 1024, quality = 0.7) => {  const canvas = document.createElement('canvas');  const ctx = canvas.getContext('2d');  if (!ctx) return null;  const scale = maxWidth / img.width;  const width = maxWidth;  const height = img.height * scale;  canvas.width = width;  canvas.height = height;  ctx.drawImage(img, 0, 0, width, height);  return canvas.toDataURL('image/jpeg', quality);};

Leave a Comment