当我运行此代码以加载 jpeg 文件时,我在 jpeg_read_scanlines 中发生崩溃我正在使用带有 VC++ 2010 的 Windows 7 64 位
我正在加载的图片是 100x75 jpg 图片。
如果您需要更多详细信息,请询问
崩溃信息是:LibTest.exe 中 0x012db29e 处的未处理异常:0xC0000005:访问冲突写入位置 0xcdcdcdcd。
void JPG_Load (const char *path, image_t *img)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
int infile;
JSAMPARRAY buffer;
int row_stride;
unsigned char *out;
infile = fopen(path,"rb");
if (infile == 0) {
memset (img, 0, sizeof(image_t));
return;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, (FILE *)infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
out = malloc(cinfo.output_width*cinfo.output_height*cinfo.output_components);
img->pixels = out;
img->width = cinfo.output_width;
img->height = cinfo.output_height;
img->bytesPerPixel = cinfo.out_color_components;
while (cinfo.output_scanline < cinfo.output_height) {
buffer = (JSAMPARRAY)out+(row_stride*cinfo.output_scanline);
jpeg_read_scanlines(&cinfo, buffer, 1);
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
}
image_t 定义为:
typedef struct {
int width;
int height;
int bytesPerPixel;
byte *pixels;
} image_t;
不要这样做。
buffer = (JSAMPARRAY)out+(row_stride*cinfo.output_scanline); // WRONG
您正在转换为 JSAMPARRAY
,这基本上是 void **
。结果是垃圾,因为那不是您拥有的数据类型:您拥有字节数组。
如果您查看文档,jpeg_read_scanlines
函数并没有指向您的缓冲区的指针。它接受一个指向扫描线数组的指针,每个扫描线都是一个指向行数据的指针。
while (cinfo.output_scanline < cinfo.output_height) {
unsigned char *rowp[1];
rowp[0] = (unsigned char *) out + row_stride * cinfo.output_scanline;
jpeg_read_scanlines(&cinfo, rowp, 1);
}
建议:添加强制转换以修复编译器错误只有在您知道强制转换是正确的情况下才有效。除非您知道类型是什么,否则不要强制转换为任何类型。
我是一名优秀的程序员,十分优秀!