/* ═══════════════════════════════════════════════════════════════ IMAGE CONVERSION, in the browser Tools → Image converter and the Media library's Download as: a picture redrawn on a canvas and saved as another format. Nothing is uploaded. Reads whatever this browser can show (JPEG, PNG, WebP, GIF's first frame, AVIF, BMP, SVG; HEIC in Safari only). JPEG has no transparency, so a JPEG's see-through parts are filled white. ═══════════════════════════════════════════════════════════════ */ export const OUTPUT_FORMATS = [ { type: 'image/jpeg', label: 'JPG', ext: 'jpg', lossy: true }, { type: 'image/png', label: 'PNG', ext: 'png', lossy: false }, { type: 'image/webp', label: 'WebP', ext: 'webp', lossy: true }, ] as const export type OutputType = (typeof OUTPUT_FORMATS)[number]['type'] /* An SVG with no size of its own is drawn this wide. */ const SVG_EDGE = 2048 function loadImage(blob: Blob): Promise { const url = URL.createObjectURL(blob) return new Promise((resolve, reject) => { const img = new Image() img.onload = () => resolve(img) img.onerror = () => reject(new Error("This browser can't read that picture.")) img.src = url }).finally(() => URL.revokeObjectURL(url)) as Promise } /** The picture as `type`; quality 0 to 1 for JPG and WebP. */ export async function convertImage(blob: Blob, type: OutputType, quality = 0.9): Promise { const img = await loadImage(blob) const width = img.naturalWidth || SVG_EDGE const height = img.naturalHeight || SVG_EDGE const canvas = document.createElement('canvas') canvas.width = width canvas.height = height const context = canvas.getContext('2d') if (!context) throw new Error("This browser can't draw the picture.") if (type === 'image/jpeg') { context.fillStyle = '#ffffff' context.fillRect(0, 0, width, height) } context.drawImage(img, 0, 0, width, height) const out = await new Promise((resolve) => canvas.toBlob(resolve, type, quality)) // A browser that can't write the format (old Safari and WebP) // hands back a PNG, or nothing. if (!out || out.type !== type) throw new Error(`This browser can't save ${type.split('/')[1].toUpperCase()}.`) return out } /** A file name with the new format's extension. */ export function renamed(name: string, type: OutputType): string { const ext = OUTPUT_FORMATS.find((f) => f.type === type)?.ext ?? 'img' const stem = name.replace(/\.[^./]+$/, '') || 'image' return `${stem}.${ext}` } /** Hands the browser a file to save. */ export function saveBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = filename document.body.appendChild(a) a.click() a.remove() setTimeout(() => URL.revokeObjectURL(url), 1000) }