使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?

Using stbi_write_png, how do you convert a rectangular byte-array of 0s and 1s to a monochrome png file?

本文关键字:png 字节数 数组 字节 转换 单色 文件 write stbi 使用      更新时间:2023-10-16

使用 stb 图像库,如何使用对 stbi_image_write 函数的调用,将一个矩形字节数组(每个元素的值为 0 或 1(转换为单色 png 图像,其中 1 表示彩色像素?这是我们到目前为止的代码:

using namespace std;
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb/stb_image_write.h"
/* ... */
const uint32_t BITMAP_SIZE = height * width;
uint8_t* bitmap = new uint8_t[BITMAP_SIZE];
for (int i = 0; i < BITMAP_SIZE; i++) // clear the bitmap
bitmap[0] = 0;
/* write 1s to some elements of bitmap */
constexpr int CHANNELS = 4; // indexed (really 1 or 0)
string filename = "my_image.png";
stbi_write_png(/* what parameters should be passed here? */); 
delete [] bitmap;

将参数传递给stbi_write_png以获得上述所需输出的正确方法是什么?

你需要 CHANNELS=1(因为它是每像素 1 个字节(。

stbi_write_png(filename.c_str(), width, height,
CHANNELS, bitmap, width * CHANNELS);