开发者

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

开发者 https://www.devze.com 2023-04-08 09:52 出处:网络
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 i

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 tha开发者_如何转开发t'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);
}


In my Graphin library you can find simple function:

bool EncodeJPGImage(image_write_function* pctl, void* streamPrm, unsigned width, unsigned height, unsigned char** rows, unsigned bpp, unsigned quality)

that does this conversion. See http://code.google.com/p/graphin/source/browse/trunk/src/imageio.cpp#412

The library: http://code.google.com/p/graphin/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号