diff --git a/src/attachments.js b/src/attachments.js index 363a102..3b44bd9 100644 --- a/src/attachments.js +++ b/src/attachments.js @@ -7,7 +7,7 @@ export async function toAttach(file, opts) { const name = file.name || 'file', mime = (file.type || 'application/octet-stream').toLowerCase(); if (isVideo(name, mime)) return compressVideo(file, opts); if (/^image\//.test(mime) || /\.(png|jpe?g|webp|gif)$/i.test(name)) { - const data = mime === 'image/webp' || /\.webp$/i.test(name) ? await asDataURL(file) : await imgToWebp(file, 2048, 94); + const data = await imgToWebp(file, 2048, 94, mime === 'image/webp' || /\.webp$/i.test(name)); return { type: 'image_url', image_url: { url: data } }; } if (mime === 'application/pdf' || /\.pdf$/i.test(name)) { diff --git a/src/utils.js b/src/utils.js index 944db57..6747b8f 100644 --- a/src/utils.js +++ b/src/utils.js @@ -16,12 +16,13 @@ export const fmtSize = b => { return (x >= 10 ? Math.round(x) : Math.round(x * 10) / 10) + ' ' + u[i]; }; export const asDataURL = f => new Promise(r => { const fr = new FileReader(); fr.onload = () => r(String(fr.result || '')); fr.readAsDataURL(f); }); -export const imgToWebp = (f, D = 96, q = 75) => new Promise((r, j) => { +export const imgToWebp = (f, D = 96, q = 75, k) => new Promise((r, j) => { if (!f) return j(); const i = new Image; i.onload = () => { - const c = document.createElement('canvas'), x = c.getContext('2d'); let w = i.width, h = i.height; + if (k && Math.max(w, h) <= D) return URL.revokeObjectURL(i.src), r(asDataURL(f)); + const c = document.createElement('canvas'), x = c.getContext('2d'); if (D > 0 && Math.max(w, h) > D) w > h ? (h = D * h / w, w = D) : (w = D * w / h, h = D); c.width = w; c.height = h; x.drawImage(i, 0, 0, w, h); r(c.toDataURL('image/webp', clamp(q, 0, 100) / 100));