我如何在C#中执行此操作?我在网上看了一眼,却找不到答案.
根据GIF规范,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
}
Run Code Online (Sandbox Code Playgroud)
毫无疑问,如果您阅读这些规范,可以对JPG和PNG进行类似的字节流检查.