c++ - 在 C/C++ 中读取图像文件

标签 c++ c jpeg

我需要读取 C/C++ 中的图像文件。如果有人可以为我发布代码,那就太好了。

我处理灰度图像,图像是 JPEG。我想将图像读入二维数组,这将使我的工作变得容易。

最佳答案

如果您决定采用最小的方法,不依赖 libpng/libjpeg,我建议使用 stb_imagestb_image_write,发现 here .

这很简单,您只需将头文件 stb_image.hstb_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

其他轻量级替代方案包括:

关于c++ - 在 C/C++ 中读取图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076475/

相关文章:

c++ - std::is_convertible 何时考虑原始类型可转换?

c# - 0MQ与NetMQ的通信

javascript - 如何捕捉和处理 QWebEnginePage 内容的变化?

c - 值在 'scanf' 之后发生变化

c - 内存管理 C 和指针的 free()

c++ - 如何使用 libjpeg 获取 JPEG 文件方向

c++ - 无法在动态链接库 HCNetSDK.dll 中找到程序入口点 NET_DVR_RealPlay_V40

java - 我如何设置我的环境来构建我自己的 ril 库?

java - 在 Java 中将图像的元数据转换为 JSON

c# - 是否可以从控件创建 JPG?