【问题标题】:What is the easiest way to turn an array of RGB values in C++ into an image file?将 C++ 中的 RGB 值数组转换为图像文件的最简单方法是什么?
【发布时间】:2011-11-25 17:22:36
【问题描述】:

我一直在网上寻找一个好的、快速的解决方案,但还没有找到任何让我满意的东西。看起来它应该是微不足道的——只需对某个库中的一个函数进行一两次调用,仅此而已——但情况似乎并非如此。 libjpeg 和 libtiff 缺乏良好的文档,人们发布的解决方案涉及了解图像的生成方式和编写大约 50 行代码。你们会如何在 C++ 中做到这一点?

【问题讨论】:

  • 我个人使用 FreeImage,但我确信还有其他图像库支持多种格式。可能是适合您特定需求的一种。

标签: c++ image jpeg tiff


【解决方案1】:

如果您希望“简单”胜过其他任何事情,请查看stb_image_write.h。

这是一个单独的头文件,包括对编写 BMP、PNG 和 TGA 文件的支持。每种格式只需一次调用:

 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);

【讨论】:

  • 这正是我想要的。工作完美。谢谢!
【解决方案2】:

最简单的方法是将其保存为Netpbm image。假设您的数组被打包成每像素 24 位,像素之间没有填充,那么您可以写出一个超级简单的标头,然后是二进制数据。例如:

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);
}

【讨论】:

    【解决方案3】:

    在我的 Graphin 库中你可以找到简单的函数:

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

    执行此转换。见http://code.google.com/p/graphin/source/browse/trunk/src/imageio.cpp#412

    图书馆:http://code.google.com/p/graphin/

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多