2026-06-04 10:26:08 -04:00
|
|
|
export type CompressionResult = {
|
|
|
|
|
blob: Blob;
|
|
|
|
|
originalSize: number;
|
|
|
|
|
compressedSize: number;
|
|
|
|
|
width: number;
|
|
|
|
|
height: number;
|
|
|
|
|
};
|
|
|
|
|
|
2026-06-05 20:22:38 -04:00
|
|
|
// Any raster image the browser can render to canvas can be compressed to JPEG.
|
|
|
|
|
// SVG is vector and must stay as-is; GIF animation is lost on canvas but static
|
|
|
|
|
// frames compress fine. Empty type string (undetected MIME) is excluded.
|
|
|
|
|
const isCompressibleType = (type: string): boolean =>
|
|
|
|
|
type.startsWith('image/') && type !== 'image/svg+xml' && type !== '';
|
2026-06-04 10:26:08 -04:00
|
|
|
|
2026-06-05 20:22:38 -04:00
|
|
|
/** 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);
|
2026-06-04 10:26:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-06-05 20:22:38 -04:00
|
|
|
* 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).
|
2026-06-04 10:26:08 -04:00
|
|
|
*/
|
2026-06-05 20:22:38 -04:00
|
|
|
export async function compressImage(
|
|
|
|
|
file: File | Blob,
|
|
|
|
|
quality = 0.82,
|
|
|
|
|
): Promise<CompressionResult | null> {
|
|
|
|
|
if (!isCompressibleType(file.type)) return null;
|
2026-06-04 10:26:08 -04:00
|
|
|
|
|
|
|
|
const img = await loadImage(file);
|
|
|
|
|
const canvas = document.createElement('canvas');
|
|
|
|
|
canvas.width = img.naturalWidth;
|
|
|
|
|
canvas.height = img.naturalHeight;
|
|
|
|
|
const ctx = canvas.getContext('2d')!;
|
|
|
|
|
ctx.drawImage(img, 0, 0);
|
|
|
|
|
|
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
|
canvas.toBlob(
|
|
|
|
|
(blob) => {
|
|
|
|
|
if (!blob) {
|
|
|
|
|
resolve(null);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
resolve({
|
|
|
|
|
blob,
|
|
|
|
|
originalSize: file.size,
|
|
|
|
|
compressedSize: blob.size,
|
|
|
|
|
width: img.naturalWidth,
|
|
|
|
|
height: img.naturalHeight,
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
'image/jpeg',
|
|
|
|
|
quality,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-05 20:22:38 -04:00
|
|
|
function loadImage(file: File | Blob): Promise<HTMLImageElement> {
|
2026-06-04 10:26:08 -04:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
const url = URL.createObjectURL(file);
|
|
|
|
|
const img = new Image();
|
|
|
|
|
img.onload = () => {
|
|
|
|
|
URL.revokeObjectURL(url);
|
|
|
|
|
resolve(img);
|
|
|
|
|
};
|
|
|
|
|
img.onerror = reject;
|
|
|
|
|
img.src = url;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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`;
|
|
|
|
|
}
|