【问题标题】:How to use libjpeg to read a JPEG from a std::istream?如何使用 libjpeg 从 std::istream 读取 JPEG?
【发布时间】:2011-09-13 17:48:26
【问题描述】:

libjpeg 可以从 FILE* 或缓冲区读取 JPEG 数据。我的数据来自std::istream。我可以将整个std::istream 读入缓冲区以与libjpeg 一起使用,但如果可能的话,我宁愿让libjpeg 直接从std::istream 中读取。如何做到这一点?

【问题讨论】:

  • 这是一个 C 库......它怎么可能使用 std::istream
  • @Marlon:如果库有正确的钩子,就可以完成桥接。例如,libpng can.

标签: c++ iostream istream libjpeg


【解决方案1】:

您只需要为您的 istream 提供包装器。例如定义一个结构体

struct JpegStream {
  jpeg_source_mgr pub;
  std::istream* stream;
  byte buffer [4096];
}

那么你需要四种方法对流进行操作:

void init_source (j_decompress_ptr cinfo)
{
    auto src = (JpegStream*)(cinfo->src);
    src->stream-> // seek to 0 here
}

boolean fill_buffer (j_decompress_ptr cinfo)
{
    // Read to buffer
    JpegStream* src = // as above
    src->pub.next_input_byte = src->buffer;
    src->pub.bytes_in_buffer = // How many yo could read

    return eof() ? FALSE : TRUE;
}

void skip (j_decompress_ptr cinfo, long count)
{
   // Seek by count bytes forward
   // Make sure you know how much you have cached and subtract that
   // set bytes_in_buffer and next_input_byte
}

void term (j_decompress_ptr cinfo)
{
    // Close the stream, can be nop
}

以及将它们绑定到 JPEG 解压缩信息结构的一种方法:

void make_stream (j_decompress_ptr cinfo, std::istream* in)
{
    JpegStream * src;

    /* The source object and input buffer are made permanent so that a series
    * of JPEG images can be read from the same file by calling jpeg_stdio_src
    * only before the first one.  (If we discarded the buffer at the end of
    * one image, we'd likely lose the start of the next one.)
    * This makes it unsafe to use this manager and a different source
    * manager serially with the same JPEG object.  Caveat programmer.
    */
    if (cinfo->src == NULL)
    {   
            /* first time for this JPEG object? */
            cinfo->src = (struct jpeg_source_mgr *)
        (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, POOL_PERMANENT,   sizeof(JpegStream));
            src = reinterpret_cast<JpegStream*> (cinfo->src);
    }

    src = reinterpret_cast<JpegStream*> (cinfo->src);
    src->pub.init_source = init_source;
    src->pub.fill_input_buffer = fill_buffer;
    src->pub.skip_input_data = skip;
    src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
    src->pub.term_source = term;
    src->stream = in;
    src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
    src->pub.next_input_byte = NULL; /* until buffer loaded */
}

调用jpeg_create_decompress 后,调用你的make_stream 函数。

【讨论】:

  • fill_buffer 是否应该返回bool?它被声明为void,但返回一个值。
  • POOL_PERMANENT 在较新的 libjpeg 中是 JPOOL_PERMANENT
  • 这是一个从内存缓冲区读取的有用示例(不是流,但仍然非常有用):cs.stanford.edu/~acoates/decompressJpegFromMemory.txt
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 2013-11-25
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多