Encoding and optimization | image-rust | Spatie      

 SPATIE  

image-rust
==========

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Image-rust](https://spatie.be/docs/image-rust/v1)  Encoding and optimization

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/image-rust/v1) 

  Encoding and optimization    
- [ Introduction ](https://spatie.be/docs/image-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/image-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/image-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/image-rust/v1/usage)
- [ Encoding and optimization ](https://spatie.be/docs/image-rust/v1/encoding-and-optimization)
- [ Testing ](https://spatie.be/docs/image-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/image-rust/v1/changelog)

 Encoding and optimization
=========================

###  On this page 

1. [ Loading and orientation ](#content-loading-and-orientation)
2. [ Quality and formats ](#content-quality-and-formats)
3. [ Optimizing saved files ](#content-optimizing-saved-files)

Loading and orientation
-----------------------------------------------------------------------------------------------------------------------------

`Image::load(path)` guesses the image format from its bytes. `Image::from_bytes(bytes)` accepts an in-memory image. Both apply EXIF orientation, including mirrored orientations, before returning. Invalid images and IO failures return `Error`. `Image::from(DynamicImage)` uses the supplied pixels as-is.

These are single-image operations. Animated formats load a single frame; animation and metadata such as EXIF and ICC profiles are not preserved on output.

Decoding uses the `image` crate's default allocation limits. If you need custom decoder limits, decode with your own `ImageReader` and construct `Image` from the result. Output transformations allocate their requested dimensions; there is no package-wide output pixel limit. Validate dimensions and memory budgets before processing untrusted requests. Work on a separate thread or blocking pool when using this synchronous API in an async application.

Quality and formats
-----------------------------------------------------------------------------------------------------------------

`quality(1..=100)` defaults to 85. The setting has a format-specific meaning:

- JPEG uses the setting directly as lossy quality. Transparency is composited over the configured background, white by default, then converted to RGB. Use an opaque background for predictable flattening.
- AVIF uses lossy quality with encoder speed 6 and requires the `avif` feature.
- PNG is always lossless. Quality 1–33 selects fast compression, 34–66 selects default compression, and 67–100 selects best compression. All three retain identical pixels.
- WebP is lossless-only. GIF, TIFF, BMP and WebP use their normal encoder settings; this quality setting does not change them. GIF may quantize colors to its palette.

`save(path)` chooses the format from the extension. `save_as(path, format)` selects it explicitly. `encode(format)` returns a `Vec<u8>` and never invokes file optimizers. Unsupported encoders return an error. Encoding completes before file writing begins, but a filesystem write failure can leave a partial file; saving does not promise atomic replacement.

```
use image::ImageFormat;
use spatie_image::Image;

let png = Image::from(pixels).quality(90)?.encode(ImageFormat::Png)?;
let loaded = Image::from_bytes(&png)?;
```

Optimizing saved files
--------------------------------------------------------------------------------------------------------------------------

Calling `.optimize()` installs the default chain from [`spatie-image-optimizer`](https://docs.rs/spatie-image-optimizer). The chain runs after the encoded output has been saved. Install the tools you want to use on `PATH`; each tool handles only its supported formats. The default chain continues after optimizer errors, including missing tools. It does not guarantee the file becomes smaller.

Use `.optimize_with(chain)` to configure tools, timeouts, logging, safe output or strict errors. Strict optimizer errors propagate as `Error::Optimize`, and the encoded file already exists at the output path. Safe output protects the optimizer stage, not the preceding save.

```
use spatie_image::Image;
use spatie_image::spatie_image_optimizer::OptimizerChain;

// An empty chain is useful when the application selects optimizers later.
let chain = OptimizerChain::new().throws(true);
Image::from(pixels).optimize_with(chain).save(&output)?;
```

The supplied optimizer supports JPEG (`jpegoptim`), PNG (`pngquant`, `optipng`), GIF (`gifsicle`), WebP (`cwebp`) and AVIF (`avifdec`, `avifenc`). Its SVG optimizer requires SVGO and Node.js, but this image-processing crate does not rasterize SVG. Consult the optimizer crate's installation guide for each tool's platform requirements.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
