RGB缓冲区到JPEG缓冲区,这有什么问题? [英] RGB buffer to JPEG buffer, what is wrong here?

查看:118
本文介绍了RGB缓冲区到JPEG缓冲区,这有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种简单的方法来将包含RGB数据的缓冲区转换为jpeg.我已经尝试过使用libjpeg,但是我根本无法使其正常工作.例如,将缓冲区另存为位图时会产生以下结果:

I need an easy way to convert an buffer containing RGB data into a jpeg. I already tried using libjpeg, but I simply cannot get it to work right. For example, while saving the buffer as a Bitmap produces this:

使用libjpeg对内存中的同一图像进行编码会产生以下结果:

Using libjpeg to encode the same image in memory produces this:

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

And saving the image directly to a file just aborts without giving a warning, error or anything.

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

I certainly need something that works!

这就是我在做的

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
}

推荐答案

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

So, I found the problem, and it was at the very end, the output file should have been initialized like this:

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

这篇关于RGB缓冲区到JPEG缓冲区,这有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆