Pure Rust WebP encoding and decoding. No C dependencies, no unsafe code.
Add to your Cargo.toml:
[dependencies]
zenwebp = "0.4"New to zenwebp? Check out the API guide that demonstrates 100% of the public API with runnable examples.
// One-shot decode
let (pixels, width, height) = zenwebp::oneshot::decode_rgba(webp_bytes)?;Or use [WebPDecoder] for two-phase decoding (inspect headers before allocating):
use zenwebp::WebPDecoder;
let webp_bytes: &[u8] = /* your WebP data */;
let mut decoder = WebPDecoder::build(webp_bytes)?;
let info = decoder.info();
println!("{}x{}, alpha={}, orientation={:?}",
info.width, info.height, info.has_alpha, info.orientation);
let mut output = vec![0u8; decoder.output_buffer_size().unwrap()];
decoder.read_image(&mut output)?;read_image output format. read_image writes the image's native format:
packed RGBA8 (4 bytes/pixel, R,G,B,A) when info.has_alpha, otherwise packed
RGB8 (3 bytes/pixel, R,G,B). It does not take a format parameter — the channel
count follows the bitstream. The buffer must be exactly output_buffer_size()
bytes (width * height * {3 or 4}); any other length returns
DecodeError::ImageTooLarge. Branch on info.has_alpha (or
[WebPDecoder::has_alpha]) before interpreting the bytes. If you always want
4-channel output regardless of the source, use oneshot::decode_rgba /
DecodeRequest::decode_rgba instead (alpha is set to 255 for opaque images).
The two-phase WebPDecoder carries the same server-safety knobs as the one-shot
path — set them on the decoder before read_image:
use zenwebp::{WebPDecoder, Limits};
let webp_bytes: &[u8] = /* untrusted WebP data */;
let mut decoder = WebPDecoder::build(webp_bytes)?;
// Reject anything bigger than your budget *before* allocating the output buffer.
decoder.set_limits(Limits {
max_total_pixels: Some(40_000_000), // 40 MP
max_memory: Some(256 * 1024 * 1024), // 256 MB
..Limits::default() // keeps the other server-safe caps
});
let mut output = vec![0u8; decoder.output_buffer_size().unwrap()];
decoder.read_image(&mut output)?; // errs if a limit is exceededuse zenwebp::{LossyConfig, EncodeRequest, PixelLayout};
let rgb_pixels: &[u8] = /* your RGB data */;
let (width, height) = (800, 600);
// Create reusable config
let config = LossyConfig::new()
.with_quality(85.0)
.with_method(4); // 0=fast, 6=best
// Encode
let webp = EncodeRequest::lossy(&config, rgb_pixels, PixelLayout::Rgb8, width, height)
.encode()?;Lossy encode accepts any interleaved or planar [PixelLayout]:
Rgb8, Rgba8, Bgr8, Bgra8, Argb8, L8, La8, and Yuv420 — pass the
variant that matches your buffer (e.g. PixelLayout::Rgba8 for 4-channel RGBA, no
pre-conversion needed). Alpha-bearing layouts encode an alpha plane; the rest are
opaque. (See Encoder Input Formats for the full matrix.)
use zenwebp::{LosslessConfig, EncodeRequest, PixelLayout};
let rgba_pixels: &[u8] = /* your RGBA data */;
let (width, height) = (800, 600);
let config = LosslessConfig::new()
.with_quality(90.0)
.with_method(6);
let webp = EncodeRequest::lossless(&config, rgba_pixels, PixelLayout::Rgba8, width, height)
.encode()?;Decode/encode return Result<_, whereat::At<E>> (At<DecodeError> /
At<EncodeError>). The At<…> wrapper records a build-time source location for
your logs; get the underlying error with err.error() (borrow) or
err.into_inner() (owned), then match the variant:
use zenwebp::DecodeError;
match zenwebp::oneshot::decode_rgba(webp_bytes) {
Ok((pixels, w, h)) => { /* `pixels` is packed RGBA8: w*h*4 bytes, R,G,B,A */ }
Err(e) => {
// `e.location()` is the whereat capture site (file:line) — log it for triage:
if let Some(loc) = e.location() {
eprintln!("decode failed at {}:{}", loc.file(), loc.line());
}
match e.error() {
DecodeError::Cancelled(_) => eprintln!("cancelled / timed out"), // 499
// pixel/dimension caps surface here; the message says which limit:
DecodeError::InvalidParameter(msg) => eprintln!("rejected: {msg}"), // 400/413
DecodeError::MemoryLimitExceeded => eprintln!("too large"), // 413
other => eprintln!("decode failed: {other:?}"), // 400/500
}
}
}The one-shot helpers decode with DecodeConfig::default(), which already
enforces a server-safe [Limits] (≤120 MP, 16384×16384, 1 GB memory). To tighten
or relax the caps, build a [DecodeConfig] with your own [Limits] and drive the
decode explicitly with [DecodeRequest]:
use zenwebp::{DecodeConfig, DecodeRequest, Limits};
// `Limits` is `#[non_exhaustive]`; spread `..Limits::default()` to keep the other
// server-safe caps, then override the fields you care about. Fields are
// `Option<…>`; `None` means "no cap on this dimension".
let config = DecodeConfig::default().limits(Limits {
max_total_pixels: Some(40_000_000), // 40 MP hard cap
max_memory: Some(256 * 1024 * 1024), // 256 MB during decode
max_width: Some(8192),
max_height: Some(8192),
..Limits::default()
});
let (rgba, w, h) = DecodeRequest::new(&config, webp_bytes).decode_rgba()?;DecodeConfig also has builder shortcuts for the common caps —
DecodeConfig::default().max_dimensions(8192, 8192).max_memory(256 << 20) — and
Limits::none() removes every cap (only for fully trusted input).
Both decode and encode accept a cooperative [enough::Stop] token, so a
long-running operation on a hostile input can be aborted from another thread
without kill-ing it (which would leak the work-in-progress allocations). Wrap
your own cancel flag — an AtomicBool, a deadline, a request-aborted handle —
in a tiny impl Stop:
use core::sync::atomic::{AtomicBool, Ordering};
use enough::{Stop, StopReason}; // add `enough = "0.4.3"` to Cargo.toml
use zenwebp::{DecodeConfig, DecodeRequest, EncodeRequest, LossyConfig, PixelLayout};
struct CancelFlag<'a>(&'a AtomicBool);
impl Stop for CancelFlag<'_> {
fn check(&self) -> Result<(), StopReason> {
if self.0.load(Ordering::Relaxed) {
Err(StopReason::Cancelled) // also StopReason::TimedOut for deadlines
} else {
Ok(())
}
}
}
let cancelled = AtomicBool::new(false);
let stop = CancelFlag(&cancelled);
// (another thread / a timeout sets `cancelled` to true to abort)
// Cancellable decode: pass the token via `.stop(...)`.
let config = DecodeConfig::default();
let decoded = DecodeRequest::new(&config, webp_bytes).stop(&stop).decode_rgba();
// Cancellable encode: pass the token via `.with_stop(...)`.
let cfg = LossyConfig::new().with_quality(75.0);
let encoded = EncodeRequest::lossy(&cfg, &rgb_pixels, PixelLayout::Rgb8, w, h)
.with_stop(&stop)
.encode();A cancelled operation returns DecodeError::Cancelled(StopReason) /
EncodeError::Cancelled(StopReason). The token is checked periodically inside the
hot loops, so cancellation latency is bounded by a chunk of work, not the whole
image. Default (enough::Unstoppable, used when you don't call .stop(...)) is
zero-cost.
Cancellation. DecodeRequest::stop() takes a &dyn enough::Stop. For a real,
thread-safe cancel/deadline token use almost_enough::Stopper
(cargo add almost-enough); a cancelled decode returns DecodeError::Cancelled:
use almost_enough::Stopper;
use std::sync::Arc;
use zenwebp::{DecodeConfig, DecodeRequest};
let stop = Arc::new(Stopper::new());
let watcher = Arc::clone(&stop);
std::thread::spawn(move || watcher.cancel()); // e.g. on deadline / client disconnect
let config = DecodeConfig::default();
let (rgba, w, h) = DecodeRequest::new(&config, webp_bytes).stop(&*stop).decode_rgba()?;use zenwebp::{LossyConfig, EncodeRequest, PixelLayout};
let (rgba, w, h) = zenwebp::oneshot::decode_rgba(input_webp)?;
let cfg = LossyConfig::new().with_quality(75.0);
// Arg order: lossy(config, pixels, LAYOUT, width, height) — the pixel layout
// comes BEFORE the dimensions. `decode_rgba` always yields `PixelLayout::Rgba8`.
let out = EncodeRequest::lossy(&cfg, &rgba, PixelLayout::Rgba8, w, h).encode()?;- Pure Rust - no C dependencies, builds anywhere Rust does
#![forbid(unsafe_code)]- memory safety guaranteed- no_std compatible - works with just
alloc, no standard library needed - SIMD accelerated - SSE2/SSE4.1/AVX2 on x86, NEON on ARM64, SIMD128 on WASM
- Full format support - lossy, lossless, alpha, animation (encode + decode), ICC/EXIF/XMP metadata, EXIF orientation parsing, mux/demux, chroma dithering
- Metadata module -
zenwebp::metadatafor extracting/embedding ICC, EXIF, and XMP in encoded WebP bytes without decoding pixels - zencodec integration - optional
zencodecfeature for unified codec trait implementations
We achieve both safety and performance through safe abstractions over CPU intrinsics:
archmageandmagetypes- token-gated safe intrinsics with runtime CPU detectionsafe_unaligned_simd- safe unaligned load/store
These abstractions may not be perfect, but we trust them over hand-rolled unsafe code.
Supports all WebP features: lossy and lossless compression, alpha channel, animation, and extended format with ICC/EXIF/XMP chunks. Output formats: RGB, RGBA, BGR, BGRA, ARGB, YUV 4:2:0, RGB565, RGBA4444, premultiplied RGBA/BGRA/ARGB. Chroma dithering matches libwebp pixel-for-pixel.
Supports lossy and lossless encoding with configurable quality (0-100) and speed/quality tradeoff (method 0-6).
use zenwebp::{LossyConfig, LosslessConfig, EncodeRequest, PixelLayout};
// Lossless encoding
let config = LosslessConfig::new().with_quality(100.0);
let webp = EncodeRequest::lossless(&config, pixels, PixelLayout::Rgba8, w, h).encode()?;
// Fast lossy encoding (larger files)
let config = LossyConfig::new().with_quality(75.0).with_method(0);
let webp = EncodeRequest::lossy(&config, pixels, PixelLayout::Rgb8, w, h).encode()?;
// High quality lossy (slower, smaller files)
let config = LossyConfig::new().with_quality(75.0).with_method(6);
let webp = EncodeRequest::lossy(&config, pixels, PixelLayout::Rgb8, w, h).encode()?;| Feature | zenwebp | libwebp |
|---|---|---|
| Lossy (VP8) | ✅ | ✅ |
| Lossless (VP8L) | ✅ | ✅ |
| Alpha channel | ✅ | ✅ |
| Animation decode + encode (ANIM/ANMF) | ✅ | ✅ |
| Extended format (VP8X) | ✅ | ✅ |
| ICC/EXIF/XMP metadata | ✅ | ✅ |
| Metadata without pixel decode | ✅ | ✅ |
| Output: RGB, RGBA | ✅ | ✅ |
| Output: BGR, BGRA | ✅ | ✅ |
| Output: ARGB | ✅ | ✅ |
| Output: YUV 4:2:0 | ✅ | ✅ |
| Output: RGB565, RGBA4444 | ✅ | ✅ |
| Premultiplied alpha output (RGBA, BGRA, ARGB) | ✅ | ✅ |
| Fancy chroma upsampling | ✅ | ✅ |
| Bilinear chroma upsampling | ✅ | ✅ |
| Nearest-neighbor upsampling | ✅ | ✅ |
| Incremental decode (partial bytes in, rows out) | ❌ | ✅ |
| Crop during decode | ❌ | ✅ |
| Scale during decode | ❌ | ✅ |
| 2-thread decode pipeline (reconstruct + filter overlap) | ❌ | ✅ width >= 512 |
| Chroma dithering (hides banding at high Q) | ✅ default off | ✅ default off |
| Memory limits | ✅ | ❌ |
| Feature | zenwebp | libwebp |
|---|---|---|
| Quality (0-100) | ✅ | ✅ |
| Method (0-6) speed/quality | ✅ | ✅ |
| Presets (Photo, Drawing, etc.) | ✅ 6 | ✅ 6 |
| Auto preset (content-aware selection) | ✅ | ❌ |
| Target file size (secant method) | ✅ | ❌ |
| Target file size (multi-pass) | ❌ | ✅ |
| Target PSNR | ✅ | ✅ |
| SNS (spatial noise shaping) | ✅ | ✅ |
| Filter strength/sharpness | ✅ | ✅ |
| Autofilter | ✅ | ✅ |
| Segments (1-4) | ✅ | ✅ |
| Token partitions | 1 | 1-8 |
| Intra16 modes (DC/V/H/TM) | ✅ | ✅ |
| Intra4 modes (10 modes) | ✅ | ✅ |
| Trellis quantization (m5-6) | ✅ | ✅ |
| Alpha channel (lossless + lossy quant) | ✅ | ✅ |
| Sharp YUV conversion | ✅ | ✅ |
| Multi-pass encoding | ✅ | ✅ |
| Near-lossless | ✅ | ✅ |
| Encoding statistics | ✅ | ✅ |
| Progress callback | ✅ | ✅ |
| Cancellation without thread killing (key for untrusted input) | ✅ | ❌ |
| Alpha encoded on 2nd thread | ❌ | ✅ |
| Feature | zenwebp | libwebp |
|---|---|---|
| Predictor transform (14 modes) | ✅ | ✅ |
| Cross-color transform | ✅ | ✅ |
| Subtract green transform | ✅ | ✅ |
| Color indexing (palette) | ✅ | ✅ |
| Palette sorting strategies | ✅ 2 | ✅ |
| Pixel bundling (2/4/8 per pixel) | ✅ | ✅ |
| Color cache (auto-sized) | ✅ | ✅ |
| LZ77 (standard + RLE + box) | ✅ | ✅ |
| TraceBackwards DP (Zopfli-style) | ✅ | ✅ |
| Meta-Huffman (spatial codes) | ✅ | ✅ |
| Multi-config testing (m5-6) | ✅ | ✅ |
| Near-lossless (pixel + residual) | ✅ | ✅ |
| AnalyzeEntropy (5 modes) | ✅ | ✅ |
| Format | zenwebp | libwebp |
|---|---|---|
| RGB, RGBA | ✅ | ✅ |
| BGR, BGRA | ✅ | ✅ |
| ARGB | ✅ | ✅ |
| YUV 4:2:0 | ✅ | ✅ |
| L8 (grayscale) | ✅ | ❌ requires conversion |
| LA8 (grayscale + alpha) | ✅ | ❌ requires conversion |
| Streaming input (push_rows) | ✅ | ❌ |
| Feature | zenwebp | libwebp |
|---|---|---|
| RIFF container read/write | ✅ | ✅ |
| VP8X extended format | ✅ | ✅ |
| ICC/EXIF/XMP read | ✅ | ✅ |
| ICC/EXIF/XMP write | ✅ | ✅ via libwebpmux |
| Animation encode | ✅ | ✅ |
| Mux API (assemble chunks) | ✅ | ✅ via libwebpmux |
| Demux API (frame iteration) | ✅ | ✅ via libwebpdemux |
| Feature | zenwebp | libwebp |
|---|---|---|
| Language | Pure Rust | C |
| Memory safety | ✅ #![forbid(unsafe_code)] |
❌ manual C memory management |
| no_std + alloc | ✅ | ❌ |
| WASM | ✅ | ✅ via Emscripten |
| WASM SIMD128 acceleration | ✅ | ✅ via SIMDe |
| SSE2 / SSE4.1 | ✅ | ✅ |
| AVX2 | ✅ | ❌ |
| NEON (ARM64) | ✅ | ✅ |
| MIPS DSP | ❌ | ✅ |
| Runtime CPU detection | ✅ | ✅ |
Bit-exact with libwebp — 0 pixel diffs on 12,825 scraped WebP files and 218 conformance files.
Tested across 14 images (CLIC2025 photos, screenshots, CID22) without -C target-cpu=native:
| Content | vs libwebp (C) |
|---|---|
| Photos (CLIC2025, 2K) | 1.09-1.12x |
| Screenshots (1K-4K) | 1.06-1.14x |
| Small photos (512-576px) | 1.10-1.15x |
Streaming architecture via zencodec's StreamingDecode trait (feature zencodec). The full decoded image never needs to exist in memory:
| Decode mode | Peak memory (2940×1912) |
|---|---|
StreamingDecode::next_batch() |
1.5 MB |
decode_rgb() (full frame) |
35 MB |
libwebp WebPDecodeRGB |
34 MB |
The streaming decoder yields 16-row RGB strips via zencodec's StreamingDecode trait, enabling strip-based pipelines (decode → resize → encode) with constant memory regardless of image size.
| Content | vs libwebp (C) |
|---|---|
| Photos (512px) | at parity or faster |
| Screenshots (2K) | 1.23-1.31x |
| Method | Speed vs libwebp | Compression |
|---|---|---|
| m4 (default) | 1.35x | 1.01x |
| m5 | 1.34x | 1.0002x |
| m6 (best) | 1.32x | 1.002x |
File sizes within 0.02% of libwebp at method 5.
| Method | Speed vs libwebp | Compression |
|---|---|---|
| m2-m4 | 1.03x (near parity) | 1.00-1.01x |
| m6 | 2.6x faster | 1.01x |
24/24 pixel-exact lossless roundtrips verified.
At the same quality setting, zenwebp produces files within 1-5% of libwebp's size with comparable visual quality.
[dependencies]
zenwebp = { version = "0.4", default-features = false }Both encoder and decoder work without std. The decoder takes &[u8] slices and the encoder writes to Vec<u8>. Only encode_to_writer() requires the std feature.
zenwebp started as a fork of image-webp, the
pure-Rust WebP crate from the image-rs project. The original
decoder and lossless encoder formed the foundation on which zenwebp was built. We're grateful
to the image-rs maintainers for their well-structured, battle-tested codebase.
From that foundation, zenwebp was substantially rewritten to achieve libwebp feature and performance parity: a ground-up lossy encoder, a redesigned streaming decoder, SIMD acceleration via archmage, and extensive optimization work across all pipelines. The lossless decoder retains the most shared DNA with image-webp.
| State of the art codecs* | zenjpeg · zenpng · zenwebp · zengif · zenavif (rav1d-safe · zenrav1e · zenavif-parse · zenavif-serialize) · zenjxl (jxl-encoder · zenjxl-decoder) · zentiff · zenbitmaps · heic · zenraw · zenpdf · ultrahdr · mozjpeg-rs · webpx |
| Compression | zenflate · zenzop |
| Processing | zenresize · zenfilters · zenquant · zenblend |
| Metrics | zensim · fast-ssim2 · butteraugli · resamplescope-rs · codec-eval · codec-corpus |
| Pixel types & color | zenpixels · zenpixels-convert · linear-srgb · garb |
| Pipeline | zenpipe · zencodec · zencodecs · zenlayout · zennode |
| ImageResizer | ImageResizer (C#) — 24M+ NuGet downloads across all packages |
| Imageflow | Image optimization engine (Rust) — .NET · node · go — 9M+ NuGet downloads across all packages |
| Imageflow Server | The fast, safe image server (Rust+C#) — 552K+ NuGet downloads, deployed by Fortune 500s and major brands |
* as of 2026
archmage · magetypes · enough · whereat · zenbench · cargo-copter
And other projects · GitHub @imazen · GitHub @lilith · lib.rs/~lilith · NuGet (over 30 million downloads / 87 packages)
Dual-licensed: AGPL-3.0 or commercial.
I've maintained and developed open-source image server software — and the 40+ library ecosystem it depends on — full-time since 2011. Fifteen years of continual maintenance, backwards compatibility, support, and the (very rare) security patch. That kind of stability requires sustainable funding, and dual-licensing is how we make it work without venture capital or rug-pulls. Support sustainable and secure software; swap patch tuesday for patch leap-year.
Your options:
- Startup license — $1 if your company has under $1M revenue and fewer than 5 employees. Get a key →
- Commercial subscription — Governed by the Imazen Site-wide Subscription License v1.1 or later. Apache 2.0-like terms, no source-sharing requirement. Sliding scale by company size. Pricing & 60-day free trial →
- AGPL v3 — Free and open. Share your source if you distribute.
See LICENSE-COMMERCIAL for details.
Upstream code from image-rs/image-webp is licensed under MIT OR Apache-2.0. Our additions and improvements are dual-licensed (AGPL-3.0 or commercial) as above.
Contributions welcome! Please feel free to open issues or pull requests.
This project builds on excellent work by others:
-
image-rs/image-webp - The foundation of this crate. The image-rs team built a complete, correct, truly-safe WebP decoder and lossless encoder. We forked their work and added SIMD acceleration, lossy encoding with full RD optimization, animation encoding, and more. If you don't need those features, consider using their crate directly for a smaller, simpler dependency.
-
libwebp (Google) - Reference implementation. Our lossy encoder closely follows libwebp's algorithms for RD optimization, trellis quantization, and mode selection. The WebP format itself is Google's creation.
-
safe_unaligned_simd - Safe unaligned SIMD operations
-
Claude (Anthropic) - AI-assisted development
Code review recommended for production use.