Skip to content

Image Compressor — Java 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 Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Image compressor: quality search to a size budget — Java (17+) port of
// the image-compressor tool. The search is codec-agnostic: an ImageWriter
// with JPEGImageWriteParam "compression quality" (or a WebP ImageWriter)
// plugs in where the stand-in encoder sits.

public final class ImageCompressor {

    private ImageCompressor() {}

    // Stand-in for canvas -> WebP/JPEG encode: encoded size at a quality.
    static long encodeSize(double quality) {
        return 12_000 + (long) (88_000 * quality); // ~100 KB at q = 1.0
    }

    // 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 when nothing fits (the TS fallback then
    // re-encodes once at the 0.05 floor).
    static double compressToBudget(long targetKb) {
        long budget = targetKb * 1024L;
        double lo = 0.05, hi = 0.95, best = -1.0;
        while (lo <= hi) {
            double mid = (lo + hi) / 2.0;
            if (encodeSize(mid) <= budget) {
                best = mid;      // fits — try a higher quality
                lo = mid + 0.05;
            } else {
                hi = mid - 0.05; // too big — step down
            }
        }
        return best;
    }

    public static void main(String[] args) {
        // 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 = compressToBudget(50L);
        if (q < 0.0) {
            System.out.println("no quality fits — falling back to the 0.05 floor");
            System.exit(1);
        }
        System.out.printf("best quality %.3f -> %d bytes%n", q, encodeSize(q));
    }
}

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 →