读取PPM文件头(类型P6),宽度缺失

Reading PPM file header (type P6), width is missing

本文关键字:P6 文件 PPM 类型 读取      更新时间:2023-10-16

假设您正在阅读这样的PPM文件:

ifstream img;
img.open("Image.ppm", ios::binary);
try
{
    if (img.fail())
    {
        throw("Can't open input file");
    }
    string header;
    int w, h, b;
    img >> header;
    cout << header << endl;
    if (header.compare("P6") != 0)
    {
        throw("Wrong format file. File needs to be P6 type!");
    }
    img >> w >> h >> b;
    cout << w << " " << h << " " << b << endl;
    if (b < 0 || b > 255)
    {
        throw("An error message"); 
    }
    img.ignore(256, 'n');
}
catch (const char *err) 
{
    fprintf(stderr, "%sn", err);
    img.close();
}

有人删除了标题中的宽度或高度值。现在b值将以字节形式读取RGB数字。是否存在if语句不会阻止程序结束的可能情况?换句话说,是否存在一种优化的方法来防止此类错误?

一个可能的问题:1. b之后的数据是二进制的,所以您的场景中的b可以是非ascii的,因此可以为0,这可以通过错误消息的测试。

在最简单的情况下,如果R值恰好是一个数字的ASCII值(48-57),G值恰好是空格的ASCII值(32),那么b将以该数字的值结束(因此不会通过测试)