2009-10-08 60 views

回答

6

根據GIF spec,gif圖像的字節流以標題的6個字節和「邏輯屏幕描述符」的7個字節開始。

邏輯屏幕描述符的第5個字節是「壓縮字段」字節。 如果圖像包含全局顏色表,則設置「打包字段」的第一位。最後三位是可用於計算全局顏色表大小的數字X,如3 x 2^(X+1)

然後遵循全局顏色表(如果存在)。要跳過這個,你需要知道它的大小,如上所示計算。

然後遵循10字節的「圖像描述符」。那些的最後一個字節是另一個「打包字段」。 如果圖像是交錯的,則設置該字節的第二位。

public bool IsInterlacedGif(Stream stream) 
    { 
    byte[] buffer = new byte[10]; 
    int read; 

    // read header 
    // TODO: check that it starts with GIF, known version, 6 bytes read 
    read = stream.Read(buffer, 0, 6); 

    // read logical screen descriptor 
    // TODO: check that 7 bytes were read 
    read = stream.Read(buffer, 0, 7); 
    byte packed1 = buffer[4]; 
    bool hasGlobalColorTable = ((packed1 & 0x80) != 0); // extract 1st bit 

    // skip over global color table 
    if (hasGlobalColorTable) 
    { 
     byte x = (byte)(packed1 & 0x07); // extract 3 last bits 
     int globalColorTableSize = 3 * 1 << (x + 1); 
     stream.Seek(globalColorTableSize, SeekOrigin.Current); 
    } 

    // read image descriptor 
    // TODO: check that 10 bytes were read 
    read = stream.Read(buffer, 0, 10); 
    byte packed2 = buffer[9]; 
    return ((packed2 & 0x40) != 0); // extract second bit 
    } 

毫無疑問的字節流的類似的檢查可以爲JPG和PNG做,如果你讀這些規範。