我遵循了 libjpeg 示例文件中的示例代码,但是我无法读取图像数据。
我有以下结构,我创建了这个结构的一个实例。
struct ImageData {
unsigned char *pixels;
long width;
long height;
};
ImageData *imageData;
下面是我的 read_JPEG_file 函数:
int read_JPEG_file (char * filename)
{
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
/* More stuff */
FILE * infile; /* source file */
JSAMPARRAY buffer; /* Output row buffer */
int row_stride; /* physical row width in output buffer */
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
return 0;
}
/* Step 1: allocate and initialize JPEG decompression object */
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return 0;
}
/* Now we can initialize the JPEG decompression object. */
jpeg_create_decompress(&cinfo);
/* Step 2: specify data source (eg, a file) */
jpeg_stdio_src(&cinfo, infile);
/* Step 3: read file parameters with jpeg_read_header() */
(void) jpeg_read_header(&cinfo, TRUE);
/* Step 4: set parameters for decompression */
/* In this example, we don't need to change any of the defaults set by
* jpeg_read_header(), so we do nothing here.
*/
/* Step 5: Start decompressor */
(void) jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
/* Make a one-row-high sample array that will go away when done with image */
buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
imageData = new ImageData;
imageData->width = cinfo.output_width;
imageData->height = cinfo.output_height;
imageData->pixels = new unsigned char [cinfo.output_width * cinfo.output_height * cinfo.output_components];
long counter = 0;
//step 6, read the image line by line
while (cinfo.output_scanline < cinfo.output_height) {
//IT ALWAYS crash ON THIS JPEG_READ_SCANLINES FUNCTION CALL BELOW
(void) jpeg_read_scanlines(&cinfo, (JSAMPARRAY)(imageData->pixels), 1);
counter +=row_stride;
}
/* Step 7: Finish decompression */
(void) jpeg_finish_decompress(&cinfo);
/* Step 8: Release JPEG decompression object */
/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_decompress(&cinfo);
fclose(infile);
/* And we're done! */
return 1;
}
在上面的步骤 6 中,它总是在这个 JPEG_READ_SCANLINES 函数上失败。我在那条线上收到了“EXC_BAD_ACCESS”信号。
有没有人有任何想法,或者有一些关于使用 libjpeg 阅读 .jpg 文件的工作示例,您可以在此处分享?我检查了我的 imageData->pixels 的大小,并将其与 jpeg 文件本身的大小进行了比较,它具有相同的大小。这个变量的内存也是动态分配的,所以我知道这不是内存问题。
有任何想法吗?