如何将unsigned char*转换为图像文件(如jpg)在c++中

How i can convert unsigned char* to image file (like jpg) in c++?

本文关键字:jpg c++ 文件 unsigned char 转换 图像      更新时间:2023-10-16

我有一个opengl应用程序,在格式unsigned char*中创建一个纹理,我要将此纹理保存在一个图像文件中,但我不知道该怎么做。有人能帮帮我吗?

这是我创建的纹理:

static unsigned char* pDepthTexBuf;

这是我使用这个纹理的代码:

glBindTexture(GL_TEXTURE_2D, depthTexID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, pDepthTexBuf);

但我怎么能保存这个纹理"pDepthTexBuf"在图像文件?

这是一个非常复杂的问题…我建议参考其他公共示例,例如:http://www.andrewewhite.net/wordpress/2008/09/02/very-simple-jpeg-writer-in-c-c/

基本上,您需要集成一个图像库,然后使用它支持的任何钩子来保存您的数据。

最简单的方法可能是使用像OpenCV这样的库,它有一些非常容易使用的机制来将RGB数据的字节数组转换为图像文件。

你可以在这里看到读取OpenGL图像缓冲区并将其存储为PNG文件的示例。保存JPG文件可能就像更改输出文件的扩展名一样简单。

// Create an OpenCV matrix of the appropriate size and depth
cv::Mat img(windowSize.y, windowSize.x, CV_8UC3);
glPixelStorei(GL_PACK_ALIGNMENT, (img.step & 3) ? 1 : 4);
glPixelStorei(GL_PACK_ROW_LENGTH, img.step / img.elemSize());
// Fetch the pixels as BGR byte values 
glReadPixels(0, 0, img.cols, img.rows, GL_BGR, GL_UNSIGNED_BYTE, img.data);
// Image files use Y = down, so we need to flip the image on the X axis
cv::flip(img, img, 0);
static int counter = 0;
static char buffer[128];
sprintf(buffer, "screenshot%05i.png", counter++);
// write the image file
bool success = cv::imwrite(buffer, img);
if (!success) {
  throw std::runtime_error("Failed to write image");
}