Skip to main content

Crate webpx

Crate webpx 

Source
Expand description

§webpx

Complete WebP encoding and decoding with ICC profiles, streaming, and animation support.

webpx provides ergonomic Rust bindings to Google’s libwebp library (FFI to the upstream C codebase).

For new projects, use zenwebp instead. zenwebp is a pure-Rust port of libwebp — equally or more capable than webpx on every axis (full feature parity: lossy / lossless, animation, alpha, ICC / EXIF / XMP, streaming, presets, limits), with native wasm32-unknown-unknown support that webpx cannot offer (libwebp requires emscripten), and #![forbid(unsafe_code)] so the whole class of FFI / memory-safety bug is structurally impossible.

Performance and compression are essentially a wash: libwebp can be up to ~35 % faster on specific photos but up to ~2.5× slower on others; encoded-size difference is at most ~0.02 % — noise.

The security argument is concrete: libwebp has a documented history of high-severity vulnerabilities (most notably CVE-2023-4863, an actively-exploited 0-click heap overflow patched out of band in every major browser), and every libwebp wrapper that has been audited — webpx included — has shipped soundness bugs (versions 0.1.0–0.1.4 are yanked; 0.2.0 + 0.2.1 fixed multiple FFI issues found across two parallel audits). zenwebp’s pure-safe-Rust implementation does not have that exposure.

webpx is maintained for users whose application already links libwebp through another path (existing C / C++ code, system package), who specifically need libwebp’s MIPS DSP code paths, or who have benchmarked their content and confirmed libwebp wins.

webpx offers:

  • Static Images: Encode/decode RGB, RGBA, and YUV formats with lossy or lossless compression
  • Animations: Create and decode animated WebP files frame-by-frame or in batch
  • Metadata: Embed and extract ICC color profiles, EXIF, and XMP data
  • Streaming: Incremental decoding for large files or network streams
  • Presets: Content-aware optimization (Photo, Picture, Drawing, Icon, Text)
  • Advanced Config: Full control over compression parameters, alpha handling, and more

§Quick Start

use webpx::{Encoder, Unstoppable};

// Create a small 2x2 RGBA image (red, green, blue, white)
let rgba_data: Vec<u8> = vec![
    255, 0, 0, 255,    // red
    0, 255, 0, 255,    // green
    0, 0, 255, 255,    // blue
    255, 255, 255, 255 // white
];

// Encode to WebP (lossy, quality 85)
let webp_bytes = Encoder::new_rgba(&rgba_data, 2, 2)
    .quality(85.0)
    .encode(Unstoppable)?;

// Decode back to RGBA
let (pixels, width, height) = webpx::decode_rgba(&webp_bytes)?;
assert_eq!((width, height), (2, 2));

§Decoding untrusted input

Limits::default() applies opinionated production caps (64 MP per frame, 256 MP cumulative, 16383×16383, 64 MiB input, 4096 frames, 5 min animation, 4 MiB metadata, 256 MiB output), so the default DecoderConfig and AnimationDecoder paths are already bounded. Override individual fields via the with_* builders on top of Limits::default(), or use Limits::none() to opt out entirely (only when the input source is fully trusted).

use webpx::{Decoder, DecoderConfig, Limits};

// Tighter than default: 16 MP per frame for a thumbnail decoder.
let limits = Limits::default().with_max_pixels(16 * 1024 * 1024);

let webp_data: &[u8] = &[];
let img = Decoder::new(webp_data)?
    .config(DecoderConfig::new().limits(limits))
    .decode_rgba()?;

See the Limits type for the per-field enforcement matrix and the decode_with_limits example for end-to-end usage across the static decoder, animation decoder, and metadata extraction paths.

§Builder API

For more control, use the builder pattern:

use webpx::{Encoder, Preset, Unstoppable};

let rgba_data: &[u8] = &[0u8; 640 * 480 * 4]; // placeholder
let webp_bytes = Encoder::new_rgba(rgba_data, 640, 480)
    .preset(Preset::Photo)  // Optimize for photos
    .quality(85.0)          // 0-100, higher = better quality
    .method(4)              // 0-6, higher = slower but smaller
    .encode(Unstoppable)?;

§Feature Flags

FeatureDefaultDescription
decodeYesDecoding support
encodeYesEncoding support
stdYesStandard library (disable for no_std)
animationNoAnimated WebP support
iccNoICC/EXIF/XMP metadata
streamingNoIncremental processing

§no_std Support

This crate supports no_std with alloc. Disable the std feature:

webpx = { version = "0.1", default-features = false, features = ["decode", "encode"] }

§Compatibility Shims

For easy migration from other WebP crates, see compat::webp and compat::webp_animation.

§Error Handling

All functions return Result<T, At<Error>> where At provides lightweight error location tracking. See the error module documentation for how to:

  • Propagate traces with .at()
  • Add your crate’s info to traces with at_crate!
  • Convert to plain errors with .into_inner()

Re-exports§

pub use error::DecodingError;
pub use error::EncodingError;
pub use error::Error;
pub use error::MuxError;
pub use error::Result;

Modules§

compat
Compatibility shims for migration from other WebP crates.
error
Error types for webpx operations.
heuristics
Resource estimation heuristics for encoding and decoding operations.

Macros§

at
Start tracing an error with crate metadata for repository links.
at_crate
Add crate boundary marker to a Result with an At<E> error.

Structs§

At
An error with location tracking - wraps any error type.
Decoder
WebP decoder with advanced options.
DecoderConfig
Decoder configuration.
EncodeStats
Encoding statistics returned after compression.
Encoder
WebP encoder with full configuration options.
EncoderConfig
WebP encoder configuration. Dimension-independent, reusable across images.
ImageInfo
Information about a WebP image.
Limits
Resource limits for decode/encode operations.
Unstoppable
A Stop implementation that never stops (no cooperative cancellation).
WebPData
Owned WebP data that wraps libwebp’s native memory allocation.
YuvPlanes
YUV plane data for planar formats.
YuvPlanesRef
Reference to YUV planes (borrowed version).

Enums§

AlphaFilter
Alpha channel filtering method.
BitstreamFormat
Bitstream format.
ColorMode
Color mode for output.
ImageHint
Hint about image content for encoder optimization.
LimitExceeded
A resource limit was exceeded.
Preset
Content-aware encoding presets.
StopReason
Why an operation was stopped.

Traits§

ResultAtExt
Extension trait for adding location tracking to Result<T, At<E>>.
Stop
Cooperative cancellation check.

Functions§

at
Wrap any value in At<E> and capture the caller’s location.
decode
Decode WebP data to typed pixels.
decode_append
Decode WebP data, appending typed pixels to an existing Vec.
decode_bgr
Decode WebP data to BGR pixels (no alpha).
decode_bgr_into
Decode WebP data directly into a pre-allocated BGR buffer (zero-copy).
decode_bgra
Decode WebP data to BGRA pixels.
decode_bgra_into
Decode WebP data directly into a pre-allocated BGRA buffer (zero-copy).
decode_into
Decode WebP data directly into a typed pixel slice.
decode_rgb
Decode WebP data to RGB pixels (no alpha).
decode_rgb_into
Decode WebP data directly into a pre-allocated RGB buffer (zero-copy).
decode_rgba
Decode WebP data to RGBA pixels.
decode_rgba_into
Decode WebP data directly into a pre-allocated RGBA buffer (zero-copy).
decode_to_img
Decode WebP data to an imgref image.
decode_yuv
Decode WebP data to YUV planes.
version
Library version information.