Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to turn an array of RGB values in C++ into an image file?

Tags:

c++

image

jpeg

tiff

I've been looking all over the net for a good, quick solution to this, and haven't found anything that has satisfied me yet. It seems like it should be trivial--just one or two calls to a function in some library and that's it--but that doesn't seem to be the case. libjpeg and libtiff lack good documentation and the solutions people have posted involve understanding how the image is produced and writing ~50 lines of code. How would you guys do this in C++?

like image 962
Andrew Avatar asked Sep 27 '11 04:09

Andrew


2 Answers

If you want "simple" over anything else, then have a look at stb_image_write.h.

This is a single header file, which includes support for writing BMP, PNG and TGA files. Just a single call for each format:

 int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
 int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
 int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
like image 143
Miguel Avatar answered Sep 23 '22 15:09

Miguel


The easiest way is to save it as a Netpbm image. Assuming that your array is packed into 24 bits per pixel with no padding between pixels, then you can write out a super-simple header followed by the binary data. For example:

void save_netpbm(const uint8_t *pixel_data, int width, int height, const char *filename)
{
    // Error checking omitted for expository purposes
    FILE *fout = fopen(filename, "wb");

    fprintf(fout, "P6\n%d %d\n255\n", width, height);
    fwrite(pixel_data, 1, width * height * 3, fout);

    fclose(fout);
}
like image 26
Adam Rosenfield Avatar answered Sep 25 '22 15:09

Adam Rosenfield