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

时间:2014-07-03 21:05:02

标签: c++ opengl unsigned-char image-file

我有一个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"在图像文件?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

最简单的方法可能是使用类似OpenCV的库,它有一些very easy to use mechanisms用于将RGB数据的字节数组转换为图像文件。

您可以看到一个读取OpenGL图像缓冲区并将其存储为PNG文件here的示例。保存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");
}