Image Compressor — TypeScript source
Shrink image file sizes entirely in your browser — fixed quality or an automatic fit to a size budget, optional max-dimension resize, batch support. Nothing uploads.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Image compressor — display snippet. The live tool adds batch support and a
// max-dimension resize; canvas-bound, so no Go twin.
export async function compressToBudget(file: File, targetKb: number): Promise<Blob> {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d')!;
ctx.drawImage(bitmap, 0, 0);
// Binary-search the quality until the blob fits the size budget.
const budget = targetKb * 1024;
const encode = (q: number) =>
new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/webp', q));
let lo = 0.05;
let hi = 0.95;
let best: Blob | null = null;
while (lo <= hi) {
const mid = (lo + hi) / 2;
const blob = await encode(mid);
if (!blob) break;
if (blob.size <= budget) {
best = blob;
lo = mid + 0.05;
} else {
hi = mid - 0.05;
}
}
return best ?? ((await encode(0.05)) as Blob);
}
Also available in 8 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →