我对jpeglib很新。我遇到以下问题。我必须将rgb栅格保存到jpeg文件中。代码:
typedef struct JpegErrorManager {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer; //callback
} JpegErrorManager;
void JpegErrorExit(j_common_ptr cinfo)
{
/* cinfo->err actually points to a jpegErrorManager struct */
JpegErrorManager* myerr = (JpegErrorManager*)cinfo->err;
/* Create the message */
(*(cinfo->err->format_message)) (cinfo, jpegLastErrorMsg);
/* Jump to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
int Write24ByteRaster2JpegFile(const char *filefullpath, char* raster, int width, int heigth)
{
struct jpeg_compress_struct info;
//struct jpeg_error_mgr jerr;
unsigned char *oneRowImgData;
FILE* file = fopen(filefullpath, "wb");
if (!file) {
SetError("Error when creating jpeg file");
return SIL_ERROR;
}
//Overriding jpeglib standard behavior on errors by setting specific error handler
JpegErrorManager jerr;
info.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = JpegErrorExit;
if (setjmp(jerr.setjmp_buffer)) //Error "callback"
{
char errormsg[210];
sprintf(errormsg, "JPEGLIB : %s", jpegLastErrorMsg);
SetError(errormsg);
jpeg_destroy_compress(&info);
fclose(file);
return SIL_ERROR;
}
// Compression parameters
//info.err = jpeg_std_error(&jerr); //> Uncomment to enable jpeglib std error behavior
jpeg_stdio_dest(&info, file);
info.image_width = width;
info.image_height = heigth;
info.input_components = 3;
info.in_color_space = JCS_RGB;
jpeg_set_defaults(&info);
jpeg_start_compress(&info, TRUE);
// Define an array, the representative picture of each row of data.
int buffsz = width * info.input_components;
oneRowImgData = (unsigned char*)malloc((size_t)buffsz);
if (!oneRowImgData)
{
SetError("Memory allocation error while writing jpeg");
return SIL_ERROR;
}
memset(oneRowImgData, 0, buffsz);
JSAMPROW row_pointer[1];
row_pointer[0] = oneRowImgData;
for (int i = 0; i <info.image_height; ++i)
{
oneRowImgData[i] = i % 256; // Dummy image data
jpeg_write_scanlines(&info, row_pointer, 1);
}
free(oneRowImgData);
jpeg_finish_compress(&info);
jpeg_destroy_compress(&info);
fclose(file);
file = NULL;
return SIL_SUCCESS;
}
在调用jpeg_stdio_dest时发生错误System.AccessViolationException。
我检查过: 是我的特定错误处理程序导致问题吗? 似乎不是来源。首先,因为我在所有其他函数中使用相同的错误处理程序(读取jpeg),它的工作完美,其次是因为我试图设置回标准的jpeglib错误行为并且有相同的错误。写文件时的正确问题?我检查了我是否有权在“filefullpath”中指定的路径中创建/写入文件。我有。
我不知道接下来要检查什么。谢谢你的帮助。
答案 0 :(得分:0)
在Google上搜索,我找到了http://www.andrewewhite.net/wordpress/2008/09/02/very-simple-jpeg-writer-in-c-c/的例子:
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo); // <-- first create compress structure
jpeg_stdio_dest(&cinfo, outfile);
在此示例中,在分配输出目标之前创建压缩结构。也许这有帮助。