我正在尝试读取 PNG 文件的宽度和高度。 这是我的代码:
struct TImageSize {
int width;
int height;
};
bool getPngSize(const char *fileName, TImageSize &is) {
std::ifstream file(fileName, std::ios_base::binary | std::ios_base::in);
if (!file.is_open() || !file) {
file.close();
return false;
}
// Skip PNG file signature
file.seekg(9, std::ios_base::cur);
// First chunk: IHDR image header
// Skip Chunk Length
file.seekg(4, std::ios_base::cur);
// Skip Chunk Type
file.seekg(4, std::ios_base::cur);
__int32 width, height;
file.read((char*)&width, 4);
file.read((char*)&height, 4);
std::cout << file.tellg();
is.width = width;
is.height = height;
file.close();
return true;
}
如果我尝试从 this image from Wikipedia 中读取示例,我得到了这些错误的值:
252097920 (should be 800)
139985408 (should be 600)
请注意,该函数不返回 false,因此宽度和高度变量的内容必须来自文件。
最佳答案
看起来你差了一个字节:
// Skip PNG file signature
file.seekg(9, std::ios_base::cur);
PNG Specification表示 header 长 8 个字节,因此您希望“9”改为“8”。位置从 0 开始。
另请注意,规范说明 integers are in network (big-endian) order , 所以你可能想要或需要使用 ntohl()或者如果您使用的是小端系统,则转换字节顺序。
关于c++ - 读取PNG header 的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083668/