How to release buffer created by libjpeg?

妖精的绣舞 提交于 2019-12-12 12:57:04

问题


I am using libjpeg to transform image buffer from OpenCV Mat and write it to a memory location

Here is the code:

bool mat2jpeg(cv::Mat frame, unsigned char **outbuffer
    , long unsigned int *outlen) {

    unsigned char *outdata = frame.data;

    struct jpeg_compress_struct cinfo = { 0 };
    struct jpeg_error_mgr jerr;
    JSAMPROW row_ptr[1];
    int row_stride;

    *outbuffer = NULL;
    *outlen = 0;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_mem_dest(&cinfo, outbuffer, outlen);
    jpeg_set_quality(&cinfo, JPEG_QUALITY, TRUE);
    cinfo.image_width = frame.cols;
    cinfo.image_height = frame.rows;
    cinfo.input_components = 1;
    cinfo.in_color_space = JCS_GRAYSCALE;

    jpeg_set_defaults(&cinfo);
    jpeg_start_compress(&cinfo, TRUE);
    row_stride = frame.cols;

    while (cinfo.next_scanline < cinfo.image_height) {
        row_ptr[0] = &outdata[cinfo.next_scanline * row_stride];
        jpeg_write_scanlines(&cinfo, row_ptr, 1);
    }

    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);


    return true;

}

The thing is I cannot deallocate outbuffer anywhere.

This is how I am using the function:

long unsigned int * __size__ = nullptr;

unsigned char * _buf = nullptr;

mat2jpeg(_img, &_buf, __size__);

both free(_buf) and free(*_buf) fails it seems i am trying to free the head of heap by doing so.

and mat2jpeg won't accept a pointer to pointer for outbuffer. any idea?


回答1:


I think your problem may be with your __size__ variable. Its not allocated anywhere. According to my reading of the libjpeg source code that means the buffer is never allocated and the program calls a fatal error function.

I think you need to call it like this:

long unsigned int __size__ = 0; // not a pointer

unsigned char * _buf = nullptr;

mat2jpeg(_img, &_buf, &__size__); // send address of __size__

Then you should be able to deallocate the buffer with:

free(_buf);



回答2:


I have verified that it is the dll that caused the issue. I tried to recompiled libjpeg as static library and everything now works like a charm.



来源:https://stackoverflow.com/questions/32587235/how-to-release-buffer-created-by-libjpeg

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