write a jpeg with libjpeg (seg fault)
Trying to write a jpeg file from some raw data using libjpeg.
It triggers a Segmentation Fault in jpeg_start_compress()
Here is the relevant part of the code :
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);
}
The problem is not with the memcpy, it does not even get to the for loop... just crash at _start_compress.
In case that is relevant, the system is Ubuntu 10.10.
You need to set an error manager:
struct jpeg_error_mgr jerr;
....
cinfo.err = jpeg_std_error(&jerr);
jpeg_set_defaults(&cinfo);
....
精彩评论