image (Rust crate)
| Language | Rust |
|---|---|
| License | MIT or Apache 2.0 |
| Repository | github.com/image-rs/image |
| Documentation | docs.rs/image |
| Depends on | pure Rust; TGA is the tga feature (on by default) |
| Read / write | yes / yes; reads palette, grayscale and true-color, raw or RLE; writes L8, La8, Rgb8, Rgba8 with RLE (default) or raw |
image is the most used Rust image crate. It decodes and encodes many formats into common buffer types (DynamicImage, RgbaImage) and adds resizing, cropping and color conversion. Its TGA codec lives in image::codecs::tga: TgaDecoder reads all common TGA variants and handles the origin bit; TgaEncoder writes grayscale, RGB and RGBA files, RLE-compressed by default.
Like most decoders it ignores the TGA 2.0 extension area (metadata, thumbnail).
Installation#
Shell
cargo add image
To build only the formats you use:
TOML
[dependencies]
image = { version = "0.25", default-features = false, features = ["tga", "png"] }
Basic usage: convert TGA to PNG#
Rust
fn main() -> Result<(), image::ImageError> {
let img = image::open("in.tga")?; // format from the extension
println!("{} x {}, {:?}", img.width(), img.height(), img.color());
img.save("out.png")?;
Ok(())
}
How to convert PNG to TGA#
save picks the format from the extension and writes RLE-compressed TGA:
Rust
let img = image::open("in.png")?;
img.save("out.tga")?;
// or explicitly:
img.save_with_format("out.tga", image::ImageFormat::Tga)?;
How to write an uncompressed TGA#
Use TgaEncoder directly and turn RLE off:
Rust
use image::codecs::tga::TgaEncoder;
use image::ExtendedColorType;
use std::fs::File;
use std::io::BufWriter;
fn write_raw_tga(img: &image::DynamicImage, path: &str) -> image::ImageResult<()> {
let rgba = img.to_rgba8();
let out = BufWriter::new(File::create(path)?);
TgaEncoder::new(out)
.disable_rle()
.encode(rgba.as_raw(), rgba.width(), rgba.height(), ExtendedColorType::Rgba8)
}
How to get TGA width and height without decoding#
Rust
use image::ImageReader;
let (w, h) = ImageReader::open("in.tga")?.into_dimensions()?;
println!("{w} x {h}");
How to load a TGA from memory#
TGA has no magic bytes, so the format can’t be guessed from content: pass it explicitly.
Rust
let bytes: &[u8] = include_bytes!("texture.tga");
let img = image::load_from_memory_with_format(bytes, image::ImageFormat::Tga)?;
let rgba = img.to_rgba8(); // top row first
How to read the original color type#
Rust
use image::codecs::tga::TgaDecoder;
use image::ImageDecoder;
use std::fs::File;
use std::io::BufReader;
let decoder = TgaDecoder::new(BufReader::new(File::open("in.tga")?))?;
println!("{:?} -> {:?}", decoder.original_color_type(), decoder.color_type());
Tips#
ImageReader::open(path)?.with_guessed_format()can’t detect TGA from content; it falls back to the extension set byopen.- Set decoder limits (
ImageReader::limits) when you decode untrusted files, to cap memory use.