RGB buffer to JPEG buffer, what is wrong here?

我们两清 提交于 2021-02-07 19:23:22

问题


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:

Bitmap Screenshot

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

enter image description here

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

I certainly need something that works!

This is what I am doing

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
}

回答1:


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);


来源:https://stackoverflow.com/questions/10482812/rgb-buffer-to-jpeg-buffer-what-is-wrong-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!