Read an image file in C/C++ into an array

c, c++, jpeg

Solution

If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using `stb_image` and `stb_image_write`, found here.

It's as simple as it gets, you just need to place the header files `stb_image.h` and `stb_image_write.h` in your folder.

Here's the code that you need to read images:

#include <stdint.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int main() {
    int width, height, bpp;

    uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);

    stbi_image_free(rgb_image);

    return 0;
}

And here's the code to write an image:

#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define CHANNEL_NUM 3

int main() {
    int width = 800; 
    int height = 800;

    uint8_t* rgb_image;
    rgb_image = malloc(width*height*CHANNEL_NUM);

    // Write your code to populate rgb_image here

    stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);

    return 0;
}

You can compile without flags or dependencies:

g++ main.cpp

Other lightweight alternatives include:

- lodepng to read and write png files

- jpeg-compressor to read and write jpeg files

Problem

How can I read a gray scale JPEG image file in C/C++ into a 2D array?

Original source

Related problems