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 39 40 41 42
| const compressImg = (file) => { const fileSize = parseFloat( Number.parseInt(file.size, 10) / 1024 / 1024 ).toFixed(2); const reader = new FileReader(); reader.readAsDataURL(file); return new Promise((resolve) => { reader.onload = (e) => { const img = new Image(); img.src = e.target.result; img.onload = () => { const w = img.width; const h = img.height; const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); let base64; canvas.setAttribute("width", w); canvas.setAttribute("height", h); ctx.drawImage(img, 0, 0, w, h); if (fileSize <= 1) { base64 = canvas.toDataURL(file.type, 1); } else if (fileSize <= 3) { base64 = canvas.toDataURL(file.type, 0.8); } else if (fileSize <= 5) { base64 = canvas.toDataURL(file.type, 0.5); } else { base64 = canvas.toDataURL(file.type, 0.1); } let fileName = file.name; fileName = fileName.replace( /^(.+)\.(.+)$/, (fullName, name, suffix) => name + Math.floor(Math.random() * (9999 - 1000) + 1000) + "." + suffix ); resolve(dataURLtoFile(base64, fileName)); }; }; }); };
|