使用 libjpegturbo 解压缩 jpeg 返回 "Empty input file"

Decompressing jpeg using libjpegturbo returning "Empty input file"

如标​​题所述,我正在尝试使用 libjpeg-turbo 读取 JPEG 文件。我在家里的 mac 上尝试了这段代码并且它起作用了,但现在我在 Windows 上并且它在调用 jpeg_read_header 时给我一个 Empty input file 错误。我已经通过 fseek/ftell 验证文件不为空,并且我得到的大小与我期望的大小一致。

我最初的想法是我可能没有以二进制模式打开文件,所以我也尝试使用 _setmode,但这似乎没有帮助。这是我的代码供参考。

int decodeJpegFile(char* filename)
{
    FILE *file = fopen(filename, "rb");

    if (file == NULL)
    {
        return NULL;
    }

    _setmode(_fileno(file), _O_BINARY);

    fseek(file, 0L, SEEK_END);
    int sz = ftell(file);
    fseek(file, 0L, SEEK_SET);


    struct jpeg_decompress_struct info; //for our jpeg info
    struct jpeg_error_mgr err; //the error handler

    info.err = jpeg_std_error(&err);
    jpeg_create_decompress(&info); //fills info structure
    jpeg_stdio_src(&info, file);
    jpeg_read_header(&info, true); // ****This is where it fails*****
    jpeg_start_decompress(&info);


    int w = info.output_width;
    int h = info.output_height;
    int numChannels = info.num_components; // 3 = RGB, 4 = RGBA
    unsigned long dataSize = w * h * numChannels;

    unsigned char *data = (unsigned char *)malloc(dataSize);
    unsigned char* rowptr;
    while (info.output_scanline < h)
    {
        rowptr = data + info.output_scanline * w * numChannels;
        jpeg_read_scanlines(&info, &rowptr, 1);
    }

    jpeg_finish_decompress(&info);
    fclose(file);

    FILE* outfile = fopen("outFile.raw", "wb");
    size_t data_out = fwrite(data, dataSize, sizeof(unsigned char), outfile);

}`

非常感谢任何帮助!

问题的核心是dll不匹配。 libjpeg 是根据 msvcrt.dll 构建的,而应用程序是针对 MSVS2015 提供的任何运行时构建的。它们不兼容,在一个运行时打开的文件指针对另一个运行时没有意义。

根据此 discussion,解决方案是避免 jpeg_stdio_src API。

您正在将 C++ true 值传递给 jpeg_read_header -- 这也可能是失败的原因。您应该改为传递 TRUE 常量。