imagerustprocedural

How do I procedurally generate images using rust-image?


I'd like to learn Rust and thought it would be fun to procedurally generate images. I've no idea where to start though... piston/rust-image? But even with that where should I begin?


Solution

  • 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: output

    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.

    NOTE:

    get_pixel_mut Deprecated since 0.24.0: Use get_pixel and put_pixel instead.