用libjpeg写一个jpeg(seg fault)

时间:2011-01-12 00:04:26

标签: c linux libjpeg

尝试使用libjpeg从一些原始数据中编写jpeg文件。

它会在jpeg_start_compress()

中触发分段错误

以下是代码的相关部分:

void write_sub_image(char *filename, int start, int end)
{
    struct jpeg_compress_struct cinfo;
    unsigned char *stride;
    JSAMPROW row_pointer[1];
    unsigned long new_width = end-start;
    int i;
    FILE *fp;

    stride = (unsigned char *)malloc( new_width * 3);

    fp = fopen(filename, "w+");

    jpeg_create_compress(&cinfo);

    jpeg_stdio_dest(&cinfo, fp);

    cinfo.image_width = new_width;
    cinfo.image_height = height;
    cinfo.input_components = 3;
    cinfo.in_color_space = JCS_RGB;

    jpeg_set_defaults(&cinfo);

    jpeg_start_compress(&cinfo, FALSE);

    for (i=0; i<height; i++) {
        memcpy (stride, image + (start + i * width) * 3, new_width * 3);
        row_pointer[0] = stride;
        jpeg_write_scanlines(&cinfo, &stride, 1);
    }

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

    fclose(fp);
}

问题不在于memcpy,它甚至没有进入for循环......只是在_start_compress崩溃。

如果相关,系统是Ubuntu 10.10。

1 个答案:

答案 0 :(得分:5)

您需要设置错误管理器:

struct jpeg_error_mgr jerr; 
....
cinfo.err = jpeg_std_error(&jerr); 
jpeg_set_defaults(&cinfo);
....