Create empty image with white background and black borders using Rust


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


use image::{ImageBuffer, RgbImage};

fn main() {

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]);

The result

The setup


name = "create-white-image"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at

image = "0.24"

Related Pages

Image - a crate to generate and manipulate images in Rust


Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo