export type CompressionResult = { blob: Blob; /** MIME type of the produced blob (currently always image/jpeg). */ type: string; originalSize: number; compressedSize: number; width: number; height: number; }; // Raster images the browser can render to canvas can be compressed to JPEG. // SVG is vector and must stay as-is. [Gitea #331] GIF and APNG are usually // animated, and a canvas keeps only the first frame, so they aren't offered. // Empty type string (undetected MIME) is excluded. const NOT_COMPRESSIBLE = new Set(['image/svg+xml', 'image/gif', 'image/apng']); const isCompressibleType = (type: string): boolean => type.startsWith('image/') && !NOT_COMPRESSIBLE.has(type); /** * Pure: whether a WebP file is animated. An animated WebP is a VP8X file * whose header has the animation flag (byte 20, bit 0x02) and an ANIM chunk. */ export function isAnimatedWebp(bytes: Uint8Array): boolean { const ascii = (at: number, len: number) => String.fromCharCode(...bytes.subarray(at, at + len)); if (bytes.length < 21 || ascii(0, 4) !== 'RIFF' || ascii(8, 4) !== 'WEBP') return false; // Bit 0x02 of the VP8X flags byte (no-bitwise: test it arithmetically). return ascii(12, 4) === 'VP8X' && Math.floor(bytes[20] / 2) % 2 === 1; } /** Pure: whether RGBA pixel data has any pixel that isn't fully opaque. */ export function hasTransparency(rgba: Uint8ClampedArray): boolean { for (let i = 3; i < rgba.length; i += 4) { if (rgba[i] !== 255) return true; } return false; } /** Returns true if this file can be compressed via canvas (any raster image type). */ export function isCompressible(file: File | Blob): boolean { return isCompressibleType(file.type); } const JPEG_OUTPUT_TYPE = 'image/jpeg'; /** * Compress an image file via canvas.toBlob → JPEG at the given quality. * Returns null if the browser cannot render the image (e.g. unsupported codec) * or if the source is left untouched to avoid data loss (see below). * * PNG is skipped entirely: it may carry an alpha channel, and re-encoding to * JPEG composites transparency onto an opaque (black) background, corrupting the * image. Any other image with transparent pixels, and animated WebP, are left * alone for the same reason (#331). Returning null makes callers fall back to uploading the lossless * original. The image is decoded with `imageOrientation: 'from-image'` so any * EXIF orientation is baked into the pixels instead of being silently dropped. */ export async function compressImage( file: File | Blob, quality = 0.82, ): Promise { if (!isCompressibleType(file.type)) return null; // Skip PNG (potential alpha) — re-encoding to JPEG would flatten transparency. if (file.type === 'image/png') return null; // [Gitea #331] An animated WebP would become a single still frame. if (file.type === 'image/webp') { try { const head = new Uint8Array(await file.slice(0, 32).arrayBuffer()); if (isAnimatedWebp(head)) return null; } catch { return null; } } let bitmap: ImageBitmap; try { bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }); } catch { // Corrupt/unsupported source: fall back to uploading the lossless original // (the caller uses the original file on a null result) rather than rejecting, // which would drop the file entirely from the Promise.allSettled upload. return null; } const { width, height } = bitmap; const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); if (!ctx) { bitmap.close(); return null; } ctx.drawImage(bitmap, 0, 0); bitmap.close(); // [Gitea #331] JPEG has no alpha: a transparent WebP (sticker, logo) came out // with a black background. Keep any image with transparency as the original. try { if (hasTransparency(ctx.getImageData(0, 0, width, height).data)) return null; } catch { return null; } return new Promise((resolve) => { canvas.toBlob( (blob) => { if (!blob) { resolve(null); return; } resolve({ blob, type: JPEG_OUTPUT_TYPE, originalSize: file.size, compressedSize: blob.size, width, height, }); }, JPEG_OUTPUT_TYPE, quality, ); }); } export function formatFileSize(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; }