Export an image

The ultimate goal of this project is to write a series of pixels (colors) to a file, for example a PNG file.

We can model a file as a 2D grid of pixels or colors. In reality, this grid is just a long array of pixels width * height.

Here is one way to model our image file (in src/rayimage/Image.hpp):

#pragma once

#include <iostream>
#include <vector>
#include "../raymath/Color.hpp"

class Image
{
private:
  unsigned int width = 0;
  unsigned int height = 0;
  std::vector<Color> buffer;
public:
  Image(unsigned int w, unsigned int h);
  Image(unsigned int w, unsigned int h, Color c);
  ~ Image();

  void SetPixel(unsigned int x, unsigned int y, Color color);
  Color GetPixel(unsigned int x, unsigned int y);

  void WriteFile(const char* filename);
};

And here is the implementation (src/rayimage/Image.cpp):

How does this code work?

  1. We use a constructor that reserves a list of Color objects. The number of elements in the list corresponds to the total number of pixels in the image.

  2. We can define specific pixels using the x and y coordinates.

  3. We can save this grid in an image. I use the lodepngarrow-up-right tool, which I downloaded and placed in the src/lodepng directory.

Remember that an image file is just a list of pixels, and each pixel is just a list of 3 numbers (one byte each). So our write function will just loop over each Color, and for each component of the color, convert the float value to a byte value and insert it into the final image array. A PNG file has a fourth component, alpha, which we are not using in this example, so we simply set it to its maximum value.

circle-check

Last updated