首页 > 解决方案 > 如何读取 png 中的 IHDR 值?

问题描述

我正在尝试使用 c++ 获取 png 图像的 IHDR 值,我仅限于使用标准 c++11-c++17,不允许使用第 3 方库。

我已成功获得正确的 png 签名,但似乎我阅读 IHDR 的方式不正确,因为我正在处理的示例 png 只有 500 宽度和 500 高度(dim500x500)但我得到了非常大的值.

我还尝试在 png 签名后跳过 16 个字节,以防我的 png 是 CgBI,但我认为并非如此。

代码

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream read_bin("yeji.png", std::ios::out | std::ios::binary);
    if (!read_bin)
    {
        std::cout << "ERROR: reading binary file!\n";
        exit(1);
    }

    unsigned char pngsign[8];
    read_bin.read(reinterpret_cast<char*>(&pngsign[0]),sizeof(unsigned char)*8);

    unsigned int IHDR_LENGTH;
    char CHUNK_TYPE[4];
    read_bin.read(reinterpret_cast<char*>(&IHDR_LENGTH),sizeof(unsigned int));
    read_bin.read(reinterpret_cast<char*>(&CHUNK_TYPE[0]),sizeof(char)*4);

    unsigned int h, w;
    read_bin.read(reinterpret_cast<char*>(&w),sizeof(unsigned int));
    read_bin.read(reinterpret_cast<char*>(&h),sizeof(unsigned int));

    unsigned char bitdepth;
    read_bin.read(reinterpret_cast<char*>(&bitdepth),sizeof(unsigned char));

    unsigned char colordepth;
    read_bin.read(reinterpret_cast<char*>(&colordepth),sizeof(unsigned char));

    unsigned char compression_method;
    read_bin.read(reinterpret_cast<char*>(&compression_method),sizeof(unsigned char));

    unsigned char filter_method;
    read_bin.read(reinterpret_cast<char*>(&filter_method),sizeof(unsigned char));

    unsigned char interlacce_method;
    read_bin.read(reinterpret_cast<char*>(&interlacce_method),sizeof(unsigned char));

    std::cout<<"PNG SIGN : ";
    for(size_t i=0; i<8; ++i) std::cout<<int(pngsign[i])<<' ';
    std::cout<<'\n';

    std::cout<<"IHDR LENGTH = "<<IHDR_LENGTH<<'\n';
    std::cout<<"CHUNK TYPE  = "<<CHUNK_TYPE<<'\n';

    std::cout<<"Width  = "<<w<<'\n';
    std::cout<<"height = "<<h<<'\n';

    std::cout<<"bitdepth   = "<<int(bitdepth)<<'\n';
    std::cout<<"colordepth = "<<int(colordepth)<<'\n';
    std::cout<<"compression_method = "<<int(compression_method)<<'\n';
    std::cout<<"filter_method      = "<<int(filter_method)<<'\n';
    std::cout<<"interlacce_method  = "<<int(interlacce_method)<<'\n';

    return 0;
}

输出

PNG SIGN : 137 80 78 71 13 10 26 10 
IHDR LENGTH = 218103808
CHUNK TYPE  = IHDR�PNG
▒

Width  = 4093706240
height = 4093706240
bitdepth   = 8
colordepth = 2
compression_method = 0
filter_method      = 0
interlacce_method  = 0

标签: c++imageimage-processingbinarypng

解决方案


推荐阅读