How do I procedurally generate images using rust-image?
As @huon answer is 6 years old, I was getting errors reproducing the result, so I wrote this,
use image::{ImageBuffer, RgbImage};
const WIDTH:u32 = 10;
const HEIGHT:u32 = 10;
fn main() {
let mut image: RgbImage = ImageBuffer::new(WIDTH, HEIGHT);
*image.get_pixel_mut(5, 5) = image::Rgb([255,255,255]);
image.save("output.png").unwrap();
}
The place to begin is the docs and the repository.
It's not immediately obvious from the landing page of the documentation, but the core type in image
is ImageBuffer
.
The new
function allows one to construct an ImageBuffer
representing an image with the given/width, storing pixels of a given type (e.g. RGB, or that with transparency). One can use methods like pixels_mut
, get_pixel_mut
and put_pixel
(the latter are below pixels_mut
in the documentation) to modify the image. E.g.
extern crate image;
use image::{ImageBuffer, Rgb};
const WIDTH: u32 = 10;
const HEIGHT: u32 = 10;
fn main() {
// a default (black) image containing Rgb values
let mut image = ImageBuffer::<Rgb<u8>>::new(WIDTH, HEIGHT);
// set a central pixel to white
image.get_pixel_mut(5, 5).data = [255, 255, 255];
// write it out to a file
image.save("output.png").unwrap();
}
which looks like:
The repo is particularly useful as a starting point, because it contains examples, in particular, it has an example of programmatically generating an image. When using a new library, I'll open the docs, and, if confused, the repo specifically to look for examples.