sinter-js
v2.0.1
Published
Browser-side image compression with format conversion, resizing, quality control, and size targeting.
Maintainers
Readme
Sinter is a browser-side image compression library for apps that need image
files smaller before upload, preview, or download. It takes a browser Blob or File,
applies the options you choose, and returns a compressed image Blob.
- JPEG, PNG, WebP, AVIF, BMP, GIF, HEIC
- Keep the input format or convert to another supported format
- Resize, quality control, and best-effort file size targeting
- Runs compression off the main UI flow in supported browsers
- Safe to import in SSR-capable apps; compression runs on the client
Install
npm install sinter-jsBasic Usage
import { sinter } from "sinter-js";
const blob = await sinter()
.toFormat("webp")
.maxQuality(80)
.maxDimensions({ width: 1200 })
.compress(file);Every setting returns a new pipeline, including copies of nested options. Repeated calls replace the whole setting; options may appear in any order after format selection. Keep the returned value when changing settings. Pipelines can be reused:
const pipeline = sinter()
.toFormat("webp")
.maxQuality(80)
.maxDimensions({ width: 1200 });
const firstBlob = await pipeline.compress(firstFile);
const secondBlob = await pipeline.compress(secondFile);Canvas or cropper Blob output works directly:
const pngBlob = await new Promise((resolve, reject) => {
canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error("canvas export failed"))), "image/png");
});
const webpBlob = await sinter()
.toFormat("webp")
.maxQuality(82)
.maxDimensions({ width: 512, height: 512 })
.targetSize(500, "KB")
.compress(pngBlob);API
Start with sinter(), choose an output format policy, then add any compression
options before calling compress(file).
await sinter()
.allowFormats(["avif", "webp"], "webp")
.codecOptions({ webp: { lossless: false } })
.maxQuality(80)
.maxDimensions({ width: 1200 })
.targetSize(1, "MB")
.timeout(30)
.compress(file);Format
| Method | Description |
|--------|-------------|
| keepFormat() | Use the input format for the output |
| toFormat(format) | Encode to one output format |
| allowFormats(allowed, fallback) | Keep the input format when it is allowed; otherwise use fallback |
Supported formats:
"jpeg" | "png" | "webp" | "avif" | "bmp" | "gif" | "heic"Compression
| Method | Description |
|--------|-------------|
| codecOptions(options) | Set encoder options for formats this pipeline can produce |
| maxQuality(n) | Set the maximum quality from 1 to 100 |
| maxDimensions({ width?, height? }) | Resize within the given bounds while preserving aspect ratio |
| targetSize(value, unit) | Try to fit the output under a target size; unit must be "KB" or "MB" |
| timeout(seconds) | Reject if compression takes longer than the limit |
| firstFrame() | Extract the first composited animation frame |
| compress(input: Blob) | Run the pipeline and return Promise<Blob>; File also works |
Codec Options
sinter()
.toFormat("avif")
.codecOptions({ avif: { speed: 4 } })
.compress(file);| Format | Options |
|--------|---------|
| jpeg | { progressive?: boolean } |
| webp | { lossless?: boolean } |
| avif | { speed?: number } |
| png | None |
| bmp, gif, heic | None |
Behavior
- Input format is detected from file bytes, not the file extension.
targetSize()is best effort. Some images may not fit the requested target.- For lossy output formats, size fitting lowers quality before reducing dimensions.
maxQuality()does not change BMP output quality.- If same-format compression would make the file larger, Sinter returns the
original bytes when no resize or size target was requested. Explicit
firstFrame()always runs, even when its output is larger.
Animation and quality
GIF, WebP, PNG (APNG), and AVIF preserve animations across conversion. Frames are
composited and processed sequentially; frame count, representable timing, and
finite/infinite playback semantics are retained. Missing loop metadata means one play.
APNG uses the public format name "png".
firstFrame() selects the first composited animation frame, excluding a separate
APNG poster. JPEG, BMP, and HEIC output automatically extract that frame. Still
inputs also work with firstFrame().
GIF quality controls the palette ceiling: unspecified/100 allows 256 colors;
otherwise max(2, round(q * 256 / 100)), including transparency. Alpha below 128
becomes transparent; other pixels become opaque. Quality 100 does not preserve
all original colors. PNG quality below 100 enables palette quantization.
HEIC quality is passed to libheif's 1–100 quality API. AVIF color and alpha share
the quality cap; speed remains 1–10 (default 10). Resizing never raises quality.
Size fitting evaluates the minimum quality/color candidate, up to seven search
steps, then up to eight 0.7× dimension reductions. It stops at unchanged dimensions
or one pixel. If the target cannot be met, the smallest valid observed result is
returned. WebP lossless: true skips lossy quality search and only reduces dimensions.
KB and MB mean 1024 and 1024² bytes. Each candidate starts from original pixels.
Migrating from v1
This is a v2 major API change. Replace dimensions() with maxDimensions() and
size() with targetSize(); the old names are removed. Assign the result of each
setter instead of relying on mutation. Repeated codecOptions() calls replace
all previous codec options, and repeated maxDimensions() calls replace the
whole bounding box. You no longer need to wrap a Blob in a File.
Browser And SSR
Sinter can be imported in SSR-capable apps because it does not access browser globals at import time.
Call compress(file) from browser client code. Other runtimes are not part of
the public API and may reject with SinterCodecError.
WASM loading
Codecs load on demand. Once the input and output formats are known, their required modules load in parallel. No manual codec registration is needed.
| Module | Contents |
| --- | --- |
| jpeg.wasm, bmp.wasm, webp.wasm | Read/write support for each format |
| gif.wasm | GIF read/write and palette quantization |
| png.wasm | PNG/APNG read/write and APNG quantization |
| avif-decoder.wasm, avif-encoder.wasm | Separate AVIF read/write support |
| heic-decoder.wasm, heic-encoder.wasm | Separate HEIC read/write support |
For example, JPEG → AVIF loads only jpeg.wasm and avif-encoder.wasm.
PNG and APNG share one module. Same-file modules are reused within a job;
workers are terminated after each job, and cross-job downloads depend on HTTP
caching. Serve WASM files with suitable cache and compression headers.
Demo-only resize/quantization comparison code is excluded from the npm build.
Errors
import { SinterValidationError, SinterCodecError } from "sinter-js";| Error | When |
|-------|------|
| SinterValidationError | Invalid input, such as an empty file or an out-of-range option |
| SinterCodecError | Compression failed, timed out, or ran outside the public browser API path |
Development
Use Bun, Zig 0.16.0, Rust with the wasm32-wasip1 target, and Emscripten 6.0.9
with CMake to build native codecs. Source archives and crate versions are pinned.
bun install
bun run assets:fetch
bun run demoThe gallery has 32 individually runnable cases, filters, downloads, independent
browser checks, and a separate upload tab. Large internet inputs stay in
~/.cache/sinter/test-assets; source, license, and hashes are in
assets/test/sources.json. Every gallery input is an unmodified web download;
source and license links are displayed on each row. Small internal regression fixtures are generated independently
with Pillow 12.1.1 by scripts/generate-patterns.py, with fixed expectations.
The diagnostics panel compares cold and warm end-to-end timings and reports
observed WASM linear-memory capacity (not whole-process or GPU memory).
License
Sinter source is MIT. Bundled codecs retain their own licenses, including
LGPL-3.0 for libheif and libde265. See
packages/module/THIRD_PARTY_NOTICES.md and licenses/ in the package.
The native sources and pinned build scripts needed to rebuild the WASM are included.
Pass an optional { signal: abortController.signal } as the second argument to
compress() to cancel browser work and terminate its Worker. Existing one-argument
calls are unchanged. Cancellation rejects with the signal’s reason.
