voxel-tracer.github.io

Development blog where I share my knowledge and projects


Project maintained by voxel-tracer Hosted on GitHub Pages — Theme by mattgraham

Load Image

How to load a png image with stb_image

Using stb_image it’s really easy to load a png image in memory.

First all the needed code is in a single header file, so you can just import that one file.

#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
include "stb_image.h"

You only need to define STB_IMAGE_IMPLEMENTATION in one of the C or C++ to create the implementation. You can optionally define STBI_ONLY_PNG to reduce your code footprint.

You can them call stbi_load like this:

int nx, ny, n;
int desired_channels = 3;
unsigned char *data = stbi_load("my_picture.png", &nx, &ny, &n, desired_channels);
if (data == NULL)
  return 1;

This will load the image in data, and populate the variables nx, ny, n, with respectively the width and height of the loaded image in pixels and the number of channels in the image. The passed desired_channels tells stbi_load how many channels the loaded data should have, in this case 3 (red, green, and blue). Make sure you check if the returned data is not null

Once the data is loaded you can access the pixels like this:

for (int y = 0, idx = 0; y < ny; y++) {
  for (int x = 0; x < nx; x++, idx++) {
    unsigned char red = data[idx * desired_channels];
    unsigned char green = data[idx * desired_channels + 1];
    unsigned char blue = data[idx * desired_channels + 2];
    // ...
  }
}

Once you are done with the loaded image, you should free the data using the following:

stbi_image_free(data);

That’s it! Take a look at stb_image as it supported a lot of image formats. In a later post I will show how we can use SDL to display the image.

Written on February 20, 2018