When we create an image the default color of each pixel is black as you can see in the empty image example. In this example we just set all the pixels to be white. We could of course set them to any color we would like expressed in RGB - red-green-blue triplets.
After setting all the pixel to white I realized that you won't be able to see the white image on the white background of this page, so I also added two more loops to set the borders of the image to black.
The source code
examples/create-white-image/src/main.rs
use image::{ImageBuffer, RgbImage};
fn main() {
white_image();
}
fn white_image() {
let width = 300;
let height = 200;
let mut img: RgbImage = ImageBuffer::new(width, height);
let red = 255 as u8;
let green = 255;
let blue = 255;
for x in 0..width {
for y in 0..height {
*img.get_pixel_mut(x, y) = image::Rgb([red, green, blue]);
}
}
for x in 0..width {
*img.get_pixel_mut(x, 0) = image::Rgb([0, 0, 0]);
*img.get_pixel_mut(x, height - 1) = image::Rgb([0, 0, 0]);
}
for y in 0..height {
*img.get_pixel_mut(0, y) = image::Rgb([0, 0, 0]);
*img.get_pixel_mut(width - 1, y) = image::Rgb([0, 0, 0]);
}
img.save("white.png").unwrap();
}
The result
The setup
examples/create-white-image/Cargo.toml
[package]
name = "create-white-image"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
image = "0.24"