繁体   English   中英

RGB缓冲区到JPEG缓冲区,这里有什么问题?

[英]RGB buffer to JPEG buffer, what is wrong here?

我需要一种简单的方法将包含RGB数据的缓冲区转换为jpeg。 我已经尝试过使用libjpeg,但我根本无法让它正常工作。 例如,将缓冲区保存为Bitmap会产生以下结果:

位图截图

使用libjpeg在内存中编码相同的图像会产生以下结果:

在此输入图像描述

并且将图像直接保存到文件中止而不会发出警告,错误或任何其他内容。

我当然需要一些有效的东西!

这就是我在做的事情

void OnKeyPress(unsigned char key, int x, int y) {
  if (key != static_cast<unsigned char>('p'))
    return;

  int width = g_current_width;
  int height = g_current_height;
  boost::scoped_array<boost::uint8_t> buffer(new boost::uint8_t[3 * width * height]);

  glReadBuffer(GL_FRONT);
  glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE,
              reinterpret_cast<GLvoid *>(buffer.get()));
  glReadBuffer(GL_BACK);

  FlipImage(buffer.get(), width, height);

  // Generate a BMP files for testing purposes
  SaveRGB("screenshot.bmp", buffer.get(), width, height);

  jpeg_compress_struct cinfo;
  jpeg_error_mgr jerr;
  cinfo.err = jpeg_std_error(&jerr);
  jerr.trace_level = 10;
  jpeg_create_compress(&cinfo);
  boost::uint8_t *jpeg_buffer_raw = NULL;
  unsigned long outbuffer_size = 0;
  jpeg_mem_dest(&cinfo, &jpeg_buffer_raw, &outbuffer_size);

  cinfo.image_width = width;
  cinfo.image_height = height;
  cinfo.input_components = 3;
  cinfo.in_color_space = JCS_RGB;
  jpeg_set_defaults(&cinfo);

  jpeg_set_quality(&cinfo, 100, true);
  jpeg_start_compress(&cinfo, true);
  int row_stride = width * 3;
  JSAMPROW row_pointer[1];
  int counter = 0;
  std::cout << boost::format("height: %d\n") % height;
  boost::uint8_t *r_buffer = buffer.get();
  while (cinfo.next_scanline < cinfo.image_height) {
    row_pointer[0] = &r_buffer[cinfo.next_scanline * row_stride];
    jpeg_write_scanlines(&cinfo, row_pointer, 1);
    std::cout << boost::format("current line: %d\n") % (counter++);
  }
  jpeg_finish_compress(&cinfo);
  jpeg_destroy_compress(&cinfo);
  std::ofstream jpegfile("screenshot.jpg");
  jpegfile.write(reinterpret_cast<const char*>(jpeg_buffer_raw), outbuffer_size);
  jpegfile.flush();
  // calling free(jpeg_buffer_raw); or delete[] jpeg_buffer_raw; generates an error
}

所以,我发现了问题,并且最后,输出文件应该像这样初始化:

std::ofstream jpegfile("screenshot.jpg", std::ios_base::out | std::ios_base::binary);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM