Image Compressor — C 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 C implementation — the same logic the interactive tool runs, in a shareable, citable form.
/* Image compressor: quality search to a size budget — C (C11) port of the
* image-compressor tool. C has no stdlib image codec, so the encoder is a
* stand-in sized like a real one (libwebp WebPEncode / libjpeg plug in
* here); the binary search over quality is the portable part. */
#include <stdio.h>
/* Stand-in for canvas -> WebP/JPEG encode: encoded size at a quality. */
typedef unsigned long (*encode_size_fn)(double quality);
/* Binary-search the quality until the encoded image fits the budget
* (targetKb * 1024) — the core of the TS compressToBudget. Returns the
* best fitting quality, or -1.0 when nothing fits (the TS fallback then
* re-encodes once at the 0.05 floor). */
double compress_to_budget(encode_size_fn encode_size, unsigned long target_kb) {
unsigned long budget = target_kb * 1024UL;
double lo = 0.05, hi = 0.95, best = -1.0;
while (lo <= hi) {
double mid = (lo + hi) / 2.0;
if (encode_size(mid) <= budget) {
best = mid; /* fits — try a higher quality */
lo = mid + 0.05;
} else {
hi = mid - 0.05; /* too big — step down */
}
}
return best;
}
/* Deterministic stand-in codec: size grows ~linearly with quality. */
static unsigned long fake_encode(double q) {
return (unsigned long)(12000.0 + 88000.0 * q);
}
int main(void) {
/* The live tool decodes the bitmap, draws it to a canvas, then searches.
* 50 KB budget: a mid-range quality fits just under it. */
double q = compress_to_budget(fake_encode, 50);
if (q < 0.0) {
printf("no quality fits — falling back to the 0.05 floor\n");
return 1;
}
printf("best quality %.2f -> %lu bytes\n", q, fake_encode(q));
return 0;
}
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 →