2012-12-29 21 views
4

我正在試驗讀取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(應爲800)
139985408(應600)

請注意,函數是而不是返回false s o寬度和高度變量的內容必須來自文件。

回答

8

看起來你已經開通過一個字節:

// Skip PNG file signature 
file.seekg(9, std::ios_base::cur); 

PNG Specification說,頭是8個字節長,所以你想要的「9」是一個「8」來代替。位置從0開始。

另外請注意,規範說integers are in network (big-endian) order,所以你可能想要或需要使用ntohl()或以其他方式轉換字節順序,如果你在一個小端系統。

可能值得使用libpngstb_image或類似的東西,而不是試圖自己解析PNG - 除非你這樣做是爲了學習。

+0

爲你+1,它現在的作品!這只是爲了學習; – ComFreek

3

當你看Portable Network Graphics Technical details,它說簽名是8個字節不是9

另外,你確定你的系統具有相同的字節順序爲PNG標準? ntohl(3)將確保正確的字節順序。也可用於windows的It's

+0

謝謝!我已經接受了他的回答,因爲你比他晚了39秒。 – ComFreek