尝试使用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.
解决方法:
您需要设置一个错误管理器:
struct jpeg_error_mgr jerr;
....
cinfo.err = jpeg_std_error(&jerr);
jpeg_set_defaults(&cinfo);
....