Build your own Paint
Follow with gitGoing further
EN/FR
02

Chapter 2 / 11

An image in memory

We build an image pixel by pixel and save it in the PPM format.

Duration40 min
Concepts
  • Vec
  • indexing
  • &mut self
  • files
  • io::Result
  • the ? operator

Before opening a window, we'll make an image and write it to a file. It's the simplest way to see what our code produces without any library: we compute pixels, save them, and open the file with an image viewer.

By the end of the chapter, we'll have this:

A gradient from black to white, with a red square in the middle

It's modest, but it's already the basis for everything else. A screen is nothing more than a grid of pixels, and each pixel is three numbers: the amount of red, green and blue.

The PPM format#

The image formats we know, like PNG or JPEG, are compressed. Writing them by hand would take hundreds of lines. We'll use a much simpler format, almost forgotten today but perfect for learning: PPM.

A PPM file starts with a small text header:

PPM file header
P6
300 200
255

P6 gives the file type, a color image stored in binary. 300 200 gives the width and height in pixels. 255 is the maximum value of each color. Right after that come the pixels, one after the other, row by row starting from the top-left corner, each one on three bytes: red, green, blue.

That's all. No compression, no metadata. If you can fill an array of bytes, you can write a PPM.

The Image struct#

Create a new file src/image.rs:

src/image.rsRust
/// An RGB image, 3 bytes per pixel, that can be saved as a PPM file.
pub struct Image {
    pub width: usize,
    pub height: usize,
    pub pixels: Vec<u8>,
}

impl Image {
    pub fn new(width: usize, height: usize) -> Image {
        Image {
            width,
            height,
            pixels: vec![0; width * height * 3],
        }
    }
}

usize is the type Rust uses for sizes and indexes: a non-negative integer, the size of a memory address on your machine. We use it for the width and height because we'll use them to index the pixel array.

Vec<u8> is an array of bytes that can grow, stored on the heap. u8 is an integer from 0 to 255, exactly what we need for a color component. The vec![0; n] macro creates a Vec of n elements, all set to 0. For a 300 × 200 image, that's 180,000 bytes, all zero, so a completely black image.

Notice that Image doesn't derive Copy, unlike Vec2. It wouldn't be possible anyway, a Vec can't be copied implicitly. And it wouldn't be a good idea: copying 180,000 bytes on every function call would be a waste. Instead, we'll lend the image with references, as we're about to see.

Changing the color of a pixel#

The pixels are stored in a one-dimensional array, but we want to work with them using (x, y) coordinates. So we need to know where pixel (x, y) is in the array.

The pixels are stored row by row. To get to row y, you skip y full rows of width pixels each, then move x pixels along the row. Pixel (x, y) is therefore pixel number x + y * width. And since each pixel takes three bytes, its first byte (the red one) is at index (x + y * width) * 3, followed by green and blue.

Your turn

Complete the line that computes the index in set_pixel.

src/image.rsRust
impl Image {
    // ...

    pub fn set_pixel(&mut self, x: usize, y: usize, r: u8, g: u8, b: u8) {
        if x >= self.width || y >= self.height {
            return;
        }
        let i: usize = todo!(); // index of the red byte of pixel (x, y)
        self.pixels[i] = r;
        self.pixels[i + 1] = g;
        self.pixels[i + 2] = b;
    }
}

The compiler will show a few warnings while the todo!() is there, because the code after it can never run. That's normal, they'll go away once the line is written.

Solution
src/image.rsRust
let i = (x + y * self.width) * 3;

No need to write : usize anymore: Rust figures it out on its own, since x, y and self.width are all usize.

Two details in this function.

First, the if at the start. If we ask for a pixel outside the image, we do nothing. Without this check, an x that's too large would land on a pixel of the next row, or even outside the array. In that last case, Rust would stop the program with an "index out of bounds" error. That's better than in C, where you'd silently write anywhere in memory, but we'd still rather have drawing outside the image simply ignored. It will make our life easier later, when a shape sticks out past the edge.

Then, &mut self. In chapter 1, our methods took self, a copy of the vector. Here, we want to modify the image itself. &mut self means we borrow the image for writing during the call: we can modify it, but we don't keep it. On the caller's side, this requires one thing: the variable must be declared with let mut, otherwise Rust refuses to let you modify it.

Filling a rectangle#

Drawing a filled rectangle means changing the color of every pixel it covers. To avoid passing seven arguments to the function, we group the three color components into a tuple (u8, u8, u8).

Your turn

Write fill_rect, which colors the rectangle with top-left corner (x, y), width w and height h. Use set_pixel in two nested loops. In Rust, a..b is the range of numbers from a (included) to b (excluded), and you access the elements of a tuple with rgb.0, rgb.1 and rgb.2.

src/image.rsRust
pub fn fill_rect(&mut self, x: usize, y: usize, w: usize, h: usize, rgb: (u8, u8, u8)) {
    todo!()
}
Solution
src/image.rsRust
pub fn fill_rect(&mut self, x: usize, y: usize, w: usize, h: usize, rgb: (u8, u8, u8)) {
    for j in y..y + h {
        for i in x..x + w {
            self.set_pixel(i, j, rgb.0, rgb.1, rgb.2);
        }
    }
}

j goes through the rows of the rectangle, i through the columns. Since set_pixel ignores pixels outside the image, a rectangle that sticks out past the edge is simply cut off, with nothing more to do.

Saving the file#

All that's left is to write the header and then the bytes to a file. Add these two lines at the very top of src/image.rs:

src/image.rsRust
use std::fs::File;
use std::io::{self, Write};

File is used to create the file. The Write trait gives access to the writing methods, and self inside the braces also imports the io module itself, which lets us write io::Result. Then add the method:

src/image.rsRust
impl Image {
    // ...

    /// Writes the image in the binary PPM format (P6): a small text header
    /// followed by the raw RGB bytes.
    pub fn save_ppm(&self, path: &str) -> io::Result<()> {
        let mut f = File::create(path)?;
        write!(f, "P6\n{} {}\n255\n", self.width, self.height)?;
        f.write_all(&self.pixels)?;
        Ok(())
    }
}

This time, the method takes &self without mut: it reads the image but doesn't modify it. &str is a borrowed string, here the path of the file.

write! works like println!, but writes to the file. We use it for the header, in text. The pixels are written as they are with write_all, which sends the whole content of the Vec in one go.

Writing a file can fail in lots of ways: full disk, protected folder, invalid name. That's why the function returns io::Result<()>: either Ok(()) if everything went well (() means "nothing", there's no value to return), or Err with a description of the error.

Rust behavior

Every operation that can fail is followed by a ?. This little symbol does a lot: if the operation returns Ok(value), it takes the value out and the code carries on. If it returns Err(e), it stops the function right away and returns Err(e) to the caller.

Without ?, the first line would look like this:

let mut f = match File::create(path) {
    Ok(f) => f,
    Err(e) => return Err(e),
};

The ? is just a short way of writing this match. The error is neither ignored nor hidden: it goes up, and it's the caller who decides what to do with it. You can only use ? in a function that itself returns a Result (or an Option), otherwise it would have nowhere to send the error.

Drawing something#

All that's left is to use all of this. Replace the contents of src/main.rs:

src/main.rsRust
mod image;
#[allow(dead_code)] // Vec2 comes back in chapter 5.
mod vec2;

use image::Image;

fn main() -> std::io::Result<()> {
    let mut img = Image::new(300, 200);

    // A horizontal gradient, from black to white.
    for y in 0..img.height {
        for x in 0..img.width {
            let shade = (x * 255 / img.width) as u8;
            img.set_pixel(x, y, shade, shade, shade);
        }
    }

    // A red square on top.
    img.fill_rect(100, 50, 100, 100, (255, 0, 0));

    img.save_ppm("out.ppm")?;
    println!("saved to out.ppm");
    Ok(())
}

A few explanations.

We keep mod vec2; even though we're not using it for now, since Vec2 comes back in chapter 5. Without the #[allow(dead_code)] attribute, the compiler would show a warning for every item in the module that's never used. The attribute tells it that this is on purpose.

main now returns std::io::Result<()>. That's what lets us use ? on save_ppm. If saving fails, the error goes up to main, and Rust prints it before ending the program. Hence the Ok(()) at the end: if we get there, everything went fine.

For the gradient, each column gets a gray between 0 (black) and 255 (white) depending on its position: column 0 is 0, and the further right you go, the closer it gets to 255. The same gray is used for red, green and blue, which gives a gray indeed. as u8 converts the result, computed as a usize, into a u8.

Pitfall

The order of operations matters with integers. If you write x / img.width * 255, the image is completely black. x is always smaller than img.width, so x / img.width is 0 in integer division, and 0 times 255 is still 0. By multiplying first, x * 255 / img.width keeps all the precision.

Run the program:

Terminal
cargo run

The program prints only one line, to say it saved the image:

Output
saved to out.ppm

A file out.ppm has appeared at the root of the project. On macOS, Preview opens it directly. On Linux, most image viewers can read it. On Windows, the default viewer doesn't know PPM: you'll need a program like GIMP or IrfanView. You should see the gradient and the red square from the image at the start of the chapter.

If you're curious, look at the size of the file: 180,015 bytes. The 180,000 bytes of pixels, plus the 15 characters of the header. There's nothing else in it.

The full src/image.rs file
src/image.rsRust
use std::fs::File;
use std::io::{self, Write};

/// An RGB image, 3 bytes per pixel, that can be saved as a PPM file.
pub struct Image {
    pub width: usize,
    pub height: usize,
    pub pixels: Vec<u8>,
}

impl Image {
    pub fn new(width: usize, height: usize) -> Image {
        Image {
            width,
            height,
            pixels: vec![0; width * height * 3],
        }
    }

    pub fn set_pixel(&mut self, x: usize, y: usize, r: u8, g: u8, b: u8) {
        if x >= self.width || y >= self.height {
            return;
        }
        let i = (x + y * self.width) * 3;
        self.pixels[i] = r;
        self.pixels[i + 1] = g;
        self.pixels[i + 2] = b;
    }

    pub fn fill_rect(&mut self, x: usize, y: usize, w: usize, h: usize, rgb: (u8, u8, u8)) {
        for j in y..y + h {
            for i in x..x + w {
                self.set_pixel(i, j, rgb.0, rgb.1, rgb.2);
            }
        }
    }

    /// Writes the image in the binary PPM format (P6): a small text header
    /// followed by the raw RGB bytes.
    pub fn save_ppm(&self, path: &str) -> io::Result<()> {
        let mut f = File::create(path)?;
        write!(f, "P6\n{} {}\n255\n", self.width, self.height)?;
        f.write_all(&self.pixels)?;
        Ok(())
    }
}

Exercises#

  1. Draw a black and white checkerboard with 25-pixel squares. Hint: the color of a pixel depends on the square it's in, (x / 25, y / 25).

  2. Draw the French flag: three vertical stripes, blue, white and red.

  3. Bonus: there's a text version of the format, P3, where each value is written out as digits, separated by spaces. Write a save_ppm_text method that saves the image in this format, then open the file in your text editor to see what an image looks like from the inside.

Solutions

1. A square is black if the sum of its coordinates is even, white otherwise:

src/main.rsRust
for y in 0..img.height {
    for x in 0..img.width {
        let shade = if (x / 25 + y / 25) % 2 == 0 { 0 } else { 255 };
        img.set_pixel(x, y, shade, shade, shade);
    }
}

2. Three rectangles that are each a third of the width:

src/main.rsRust
let band = img.width / 3;
img.fill_rect(0, 0, band, img.height, (0, 85, 164));
img.fill_rect(band, 0, band, img.height, (255, 255, 255));
img.fill_rect(2 * band, 0, img.width - 2 * band, img.height, (239, 65, 53));

The last stripe takes everything that's left, so there's no black column if the width isn't divisible by 3.

3. Same header with P3, then the values written one by one as text:

src/image.rsRust
pub fn save_ppm_text(&self, path: &str) -> io::Result<()> {
    let mut f = File::create(path)?;
    writeln!(f, "P3\n{} {}\n255", self.width, self.height)?;
    for value in &self.pixels {
        write!(f, "{value} ")?;
    }
    Ok(())
}

The file is more than three times larger than the binary version, but you can read it and even edit it by hand.

Recap#

  • An image is an array of bytes: three per pixel, stored row by row. Pixel (x, y) starts at index (x + y * width) * 3.
  • Vec<u8> stores these bytes, and vec![0; n] creates n of them set to zero.
  • &self borrows a value to read it, &mut self to modify it. To modify a variable, it must be declared with let mut.
  • An operation that can fail returns a Result, and ? sends the error up to the caller.
  • main can return a Result, which lets you use ? all the way into main.
Following along with git?

This chapter matches the tag ch02-ppm.

In chapter 3, we move on to real shapes: rectangles, but also circles and lines, and we see how to decide which pixels to light up to draw a circle.

On this page

  1. The PPM format
  2. The Image struct
  3. Changing the color of a pixel
  4. Filling a rectangle
  5. Saving the file
  6. Drawing something
  7. Exercises
  8. Recap
← PreviousChapter 12D vectorsContentsNext →Chapter 3Drawing shapes

Build your own Paint

A tutorial by theZackD

The code on GitHubFound a mistake? Open an issueCode under the MIT license