Skip to content

imazen/zenwebp

Repository files navigation

zenwebp CI crates.io docs.rs MSRV license codecov

Pure Rust WebP encoding and decoding. No C dependencies, no unsafe code.

Getting Started

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.

Decode a WebP image

// 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)?;

Encode to WebP (Lossy)

use 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()?;

Encode to WebP (Lossless)

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()?;

Features

  • 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::metadata for extracting/embedding ICC, EXIF, and XMP in encoded WebP bytes without decoding pixels
  • zencodec integration - optional zencodec feature for unified codec trait implementations

Safe SIMD

We achieve both safety and performance through safe abstractions over CPU intrinsics:

These abstractions may not be perfect, but we trust them over hand-rolled unsafe code.

Decoder

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.

Encoder

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 Comparison with libwebp

Decoder

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

Encoder (Lossy VP8)

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

Encoder (Lossless VP8L)

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)

Encoder Input Formats

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)

Container / Metadata

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

Platform / Build

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

Performance

Lossy decoder benchmarks

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.

Lossless decoder benchmarks

Content vs libwebp (C)
Photos (512px) at parity or faster
Screenshots (2K) 1.23-1.31x

Lossy encoder benchmarks

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.

Lossless encoder benchmarks

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.

Quality

At the same quality setting, zenwebp produces files within 1-5% of libwebp's size with comparable visual quality.

no_std Support

[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.

Credits

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.

Image tech I maintain

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

General Rust awesomeness

archmage · magetypes · enough · whereat · zenbench · cargo-copter

And other projects · GitHub @imazen · GitHub @lilith · lib.rs/~lilith · NuGet (over 30 million downloads / 87 packages)

License

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.

Our open-source products

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.

Contributing

Contributions welcome! Please feel free to open issues or pull requests.

Credits

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.

  • archmage & magetypes - Safe SIMD abstractions

  • safe_unaligned_simd - Safe unaligned SIMD operations

  • Claude (Anthropic) - AI-assisted development

Code review recommended for production use.

About

No description, website, or topics provided.

Resources

License

AGPL-3.0, Unknown licenses found

Licenses found

AGPL-3.0
LICENSE-AGPL3
Unknown
LICENSE-COMMERCIAL

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages