使用libjpeg 12位时jpeg_write_scanlines segfaults

时间:2019-01-24 22:22:41

标签: opencv segmentation-fault jpeg libjpeg

我正在尝试将16位png转换为12位jpeg。这里给出了使用libjpeg进行编码的代码。 img的类型为cv::Mat,而img_buffer的类型为JSAMPLE*在头文件中定义。

void png2jpeg::writejpeg(char* filename, int quality)
{

    //create a malloc for the buffer
    img_buffer = (JSAMPLE*)malloc(img.size().width*img.size().height*sizeof(JSAMPLE));

    std::memcpy(img_buffer,img.data,img.size().width*img.size().height*sizeof(JSAMPLE));

    // create a jpeg structure
    struct jpeg_compress_struct cinfo;

    // create a jpeg error manager
    struct jpeg_error_mgr jerr;

    //create a standard setup jpeg error handler
    cinfo.err = jpeg_std_error(&jerr);

    // Open the destination file
    FILE* destjpegfile;
    if((destjpegfile = fopen(filename,"wb"))==NULL)
    {
        exit(-1);
    }

    // Create a jpeg compress object
    jpeg_create_compress(&cinfo);

    // assign outfile to jpeg object
    jpeg_stdio_dest(&cinfo, destjpegfile);

    // set image specific parameters
    cinfo.image_height = img.size().height;
    cinfo.image_width = img.size().width;
    cinfo.input_components = 3;
    cinfo.in_color_space = JCS_RGB;

    // set jpeg defaults
    jpeg_set_defaults(&cinfo);

    // set jpeg quality
    jpeg_set_quality(&cinfo,quality,TRUE);

    // start jpeg compression
    jpeg_start_compress(&cinfo, TRUE);

    // Create JSAMPLE row pointer and variable to hold row width
    JSAMPROW row_pointer[1];
    int row_stride = img.size().width * 3;


    // begin the actual compression
    while (cinfo.next_scanline < cinfo.image_height)
    {
        row_pointer[0] = &img_buffer[cinfo.next_scanline * row_stride];
        (void)jpeg_write_scanlines(&cinfo,row_pointer,1);
    }

    // finish compression
    jpeg_finish_compress(&cinfo);

    // close the file
    fclose(destjpegfile);

    // destroy the jpeg object
    jpeg_destroy_compress(&cinfo);

    std::cout <<"compression successfully completed"<<std::endl;

}

此代码在我使用8位libjpeg时有效,但是在使用12位libjpeg时执行(void)jpeg_write_scanlines(&cinfo,row_pointer,1);行时会出现段错误。我不确定我要去哪里错了。

谢谢

0 个答案:

没有答案