Expand description
nopng — a minimal, no_std PNG encoder/decoder.
See decode_image, encode_image, inspect_image, and ImageSpec for the main API.
§Examples
Encode a 2x2 RGBA8 image:
let spec = nopng::ImageSpec::new(2, 2, nopng::PixelFormat::Rgba8);
let pixels = vec![255u8; spec.data_len()]; // white, fully opaque
let png_bytes = nopng::encode_image(&spec, &pixels)?;Decode a PNG and convert to RGBA8:
let (spec, pixels) = nopng::decode_image(&png_bytes)?;
let rgba = nopng::reformat_pixels(&spec.pixel_format, &pixels, &nopng::PixelFormat::Rgba8)?;Decode in the PNG’s native format and inspect it:
let (spec, pixels) = nopng::decode_image(&png_bytes)?;
match spec.pixel_format {
nopng::PixelFormat::Rgba8 => { /* 4 bytes per pixel */ }
nopng::PixelFormat::Gray8 => { /* 1 byte per pixel */ }
_ => { /* ... */ }
}Pre-inspect a PNG to learn its format before decoding:
let spec = nopng::inspect_image(&png_bytes)?;
println!("{}x{}", spec.width, spec.height);Inspect, decode, and conditionally reformat:
let info = nopng::inspect_image(&png_bytes)?;
let (spec, pixels) = nopng::decode_image(&png_bytes)?;
// Only reformat when the native format isn't already RGBA8.
let rgba = if spec.pixel_format == nopng::PixelFormat::Rgba8 {
pixels
} else {
nopng::reformat_pixels(&spec.pixel_format, &pixels, &nopng::PixelFormat::Rgba8)?
};
assert_eq!(rgba.len(), info.width as usize * info.height as usize * 4);Encode a 4-colour indexed (palette) image:
let palette = vec![
255, 0, 0, // index 0: red
0, 255, 0, // index 1: green
0, 0, 255, // index 2: blue
255, 255, 0, // index 3: yellow
];
let spec = nopng::ImageSpec::new(
2, 2,
nopng::PixelFormat::Indexed8 { palette, trns: None },
);
let indices = vec![0, 1, 2, 3]; // one index per pixel
let png_bytes = nopng::encode_image(&spec, &indices)?;Convert pixel data between formats without encoding/decoding:
// RGB8 pixels (3 bytes each)
let rgb = vec![255, 0, 0, 0, 255, 0]; // red, green
let rgba = nopng::reformat_pixels(
&nopng::PixelFormat::Rgb8,
&rgb,
&nopng::PixelFormat::Rgba8,
)?;
assert_eq!(rgba, &[255, 0, 0, 255, 0, 255, 0, 255]);Structs§
- Image
Spec - Image metadata describing dimensions, pixel format and interlacing.
Enums§
- Error
- Errors returned by decoding and encoding operations.
- Pixel
Format - Describes the pixel layout of image data in a flat
&[u8]buffer.
Functions§
- decode_
image - Decodes PNG bytes into an
ImageSpecand pixel data. - encode_
image - Encodes an image described by
specinto PNG bytes. - inspect_
image - Reads PNG metadata from the PNG signature,
IHDR,PLTE, andtRNSchunks, stopping at the firstIDAT. - reformat_
pixels - Converts pixel data from one
PixelFormatto another.