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++?
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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With