2012-05-13 43 views
0

我目前正在編寫我自己的png閱讀器,我正在研究各個塊的讀取,並且它似乎正確地讀取了前兩個塊,但是當涉及到IDAT塊時,它顯示爲 產生了一個荒謬的大小。PNG塊讀取器,無效長度

bool LoadImage(char * path, Image * target) 
{ 
std::ifstream file; 

file.open("Lenna.png", std::ios::in | std::ios::binary); 
if(!file.is_open()) 
    return -false; 

std::cout << "Opened file : Lenna.png" << std::endl; 
struct stat filestatus; 
if (stat("Lenna.png", &filestatus) != 0) 
    return false; 

unsigned int fileSize = filestatus.st_size; 
unsigned int bytesRead = 8; 
file.seekg(8, std::ios::beg); 

while(bytesRead < fileSize) 
{ 
    //Read the length, type, then the data and at last the crc(Cyclic redundancy crap, whatever that may be) 
    char length [4]; 
    file.read(length, 4); 
    //Reverse the 4 bytes due to network type writing. 
    unsigned int dataLength = (length[0] << 24) | (length[1] << 16) | (length[2] << 8) | length[3]; 
    char type [4]; 
    file.read(type, 4); 
    char * data = new char[dataLength]; 
    file.read(data, dataLength); 
    char crc [4]; 
    file.read(crc, 4); 
    bytesRead += 12 + dataLength; 
} 

return true; 
} 

使用調試器讀取所述第一2塊作爲

類型:IDHR
長度:13個字節

類型:sRGB的
長度:1個字節

類型:IDAT
長度:4294967201個字節

這是大約2.3 gb的數據和png是462kb。任何想法爲什麼會出錯?

源圖片:http://i.cubeupload.com/sCHXFV.png

+1

文件中相應字節的值是什麼? –

+0

這裏是十六進制編輯器中初始值的截圖。 http://i.cubeupload.com/YiruKg.png – Xyro

+0

請將該十六進制轉儲的文本內容粘貼到您的問題中。 –

回答

2

問題是與字節順序和左移的逆轉。移位操作結果的符號與正在移位的值的符號相同。所以轉移一個簽名的char會表現出與你期望的不同。

要修復,請將length數組的類型更改爲unsigned char

1

您需要聲明長度unsigned char,因此字節值> = 128的符號擴展名不會是字節。你是如何以0xffffffa1結束的,你還是負值。

相關問題