Search code examples
c++qtjpeglibjpegqbytearray

Load jpeg image texture with libjpeg from QByteArray


Hi I have a QByteArray of a jpeg image which I obtained from a QNetworkReply. I see everywhere jpeg image read from file and decompressed like this,

FILE * infile;
......
if ((infile = fopen(filename, "rb")) == NULL) 
{
     fprintf(stderr, "can't open %s\n", filename);
     exit(1);
}
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, 0);
jpeg_start_decompress(&cinfo);

Then

while (scan lines remain to be read)
      jpeg_read_scanlines(...);

But how do I read it from the QByteArray instead of a file/stdio stream?


Solution

  • Use

    void jpeg_mem_src(j_decompress_ptr cinfo, unsigned char * inbuffer,
                  unsigned long insize);
    

    instead of jpeg_stdio_src

     QByteArray qarr;
    
     jpeg_decompress_struct cinfo;
     jpeg_mem_src(&cinfo, qarr.data(), qarr.size());
     jpeg_read_header(&cinfo, TRUE);
     jpeg_start_decompress(&cinfo);
    
     /// etc..