How to Procedurally Generate Images Using Rust-Image
In this article, we will learn about procedurally generating images using rust-image.
Procedurally Generate Images Using Rust-Image
Crate Image
This crate provides native Rust implementations for image encoding and decoding and fundamental image manipulation functions. Additional documentation is also available in the README.md file, viewed conveniently on GitHub.
This library provides solutions for two fundamental issues: a unified interface for image encodings and simple generic buffers for their content. Each feature is usable independently of the others.
Focus is placed on a small, stable set of everyday operations that additional specialized crates can supplement. Additionally, the library favors secure solutions with few dependencies.
To load image using io::Reader:
use std::io::Cursor;
use image::io::Reader as ImageReader;
let img_one = ImageReader::open("imagetest.png")?.decode()?;
let img_two = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?.decode()?;
To save the image:
img.save("theimage.jpg")?;
let mut bytes: Vec<u8> = Vec::new();
img2.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)?;
Image Buffers
The two primary image storage formats:
Image bufferthat stores statically typed image data.DynamicImageis an enumeration over supportedImageBufferformats that support conversions between them.
In addition to a few specialized options:
GenericImagetrait for mutable image buffers.GenericImageViewtrait for read-only GenericImage references.flatmodule containing interoperability types for generic channel matrices and foreign interfaces.
All provided image processing functions operate on types that implement the GenericImageView and GenericImage characteristics and return an ImageBuffer. All image format decoders implement the ImageDecoder trait, which offers fundamental methods for retrieving image metadata and decoding images.
Some formats additionally offer ImageDecoderExt implementations that permit decoding of only a portion of an image at a time.
The most crucial decoding techniques are:
- Dimensions: Returns a tuple with the width and height of the image.
- color type: Returns the color type of the image data output by this decoder.
- read image: It decodes the entire image into a byte array.
Dynamic Image
A DynamicImage enumerates all supported ImageBuffer<P> types. Its precise image type is determined during execution.
It is the type that is returned when an image is opened. DynamicImage reimplements all image processing functions for convenience.
For RGBA pixels, DynamicImage implements the GenericImageView and GenericImage traits.