image (Rust crate, TIFF)
| Language | Rust |
|---|---|
| License | MIT or Apache 2.0 |
| Repository | github.com/image-rs/image |
| Documentation | docs.rs/image, codecs::tiff |
| Depends on | the tiff crate (feature tiff, on by default) |
| Read / write | read: first page, 8/16-bit and float grayscale, RGB, RGBA, CMYK; write: uncompressed, single page |
The image crate loads many formats into one DynamicImage type and saves to any of them. For TIFF it uses the tiff crate. image::open detects TIFF from the file contents; save picks TIFF from the .tif / .tiff extension. It includes resize, crop, rotate, blur and color conversion.
Limits: it reads only the first page, writes uncompressed single-page files and exposes no TIFF tags other than the ICC profile and XMP. Use the tiff crate directly for pages, tags, compression or BigTIFF output.
Installation#
Shell
cargo add image
To build only TIFF and PNG support:
TOML
[dependencies]
image = { version = "0.25", default-features = false, features = ["tiff", "png"] }
Basic usage: convert TIFF to PNG#
Rust
fn main() -> Result<(), image::ImageError> {
let img = image::open("in.tif")?;
println!("{} x {}, {:?}", img.width(), img.height(), img.color());
img.save("out.png")?;
Ok(())
}
How to convert PNG or JPEG to TIFF#
Rust
let img = image::open("in.jpg")?;
img.save("out.tif")?; // extension selects TIFF
How to resize a TIFF#
Rust
use image::imageops::FilterType;
let img = image::open("in.tif")?;
let small = img.resize(1200, 1200, FilterType::Lanczos3); // fits inside 1200x1200
small.save("small.tif")?;
How to get TIFF dimensions without decoding#
Rust
let (width, height) = image::image_dimensions("in.tif")?;
println!("{width} x {height}");
How to write TIFF to memory#
Rust
use std::io::Cursor;
use image::ImageFormat;
let mut bytes: Vec<u8> = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), ImageFormat::Tiff)?;
The TIFF encoder needs a writer that implements Seek, hence the Cursor.
Tips#
- 16-bit TIFFs load as
ImageLuma16,ImageRgb16orImageRgba16; callimg.to_rgb8()for 8-bit output. - Use
image::ImageReader::open(path)?.with_guessed_format()?.decode()?when the extension is wrong or missing.