我需要读取 C/C++ 中的图像文件。如果有人可以为我发布代码,那就太好了。
我处理灰度图像,图像是 JPEG。我想将图像读入二维数组,这将使我的工作变得容易。
最佳答案
如果您决定采用最小的方法,不依赖 libpng/libjpeg,我建议使用 stb_image
和 stb_image_write
,发现 here .
这很简单,您只需将头文件 stb_image.h
和 stb_image_write.h
放在您的文件夹中。
这是您读取图像所需的代码:
#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int main() {
int width, height, bpp;
uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);
stbi_image_free(rgb_image);
return 0;
}
这是编写图像的代码:
#include <stdint.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define CHANNEL_NUM 3
int main() {
int width = 800;
int height = 800;
uint8_t* rgb_image;
rgb_image = malloc(width*height*CHANNEL_NUM);
// Write your code to populate rgb_image here
stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);
return 0;
}
您可以在没有标志或依赖项的情况下进行编译:
g++ main.cpp
其他轻量级替代方案包括:
- lodepng读取和写入 png 文件
- jpeg-compressor读写jpeg文件
关于c++ - 在 C/C++ 中读取图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076475/