1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
async function compressImage(file, maxWidth = 1920, maxHeight = 1080, quality = 0.9) { return new Promise((resolve) => { const img = new Image(); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d');
img.onload = () => { let width = img.width; let height = img.height;
if (width > maxWidth || height > maxHeight) { const ratio = Math.min(maxWidth / width, maxHeight / height); width *= ratio; height *= ratio; }
canvas.width = width; canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob( (blob) => resolve(new File([blob], file.name, { type: file.type })), file.type, quality ); };
img.src = URL.createObjectURL(file); }); }
|