c++ - 读取PNG header 的宽度和高度

标签 c++ image file file-io png

我正在尝试读取 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()或者如果您使用的是小端系统,则转换字节顺序。

可能值得使用 libpngstb_image或类似的东西,而不是尝试自己解析 png——除非你这样做是为了学习。

关于c++ - 读取PNG header 的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083668/

相关文章:

php - 如何获取添加到目录的最后一个文件的名称

c++ - 英特尔 SGX 将整数从应用程序传递到 Enclave

javascript - 在 MongoDB 中存储 dataURL 以通过本地 URL (JS) 访问它

java - 如何缩放 BufferedImage

Javascript if 语句插入图像

Java:打开文件 (Windows + Mac)

c++ - 计算整数中的位数(负整数?)

C++ Worker threads with Builder (Borland Libraries)

c++ - 如何知道现有的内部服务名称( lpServiceName )以停止它

c - 大型数据集的高效输出格式?