我正在研究 my other question的解决方案,它正在读取PNG的’zTXt’块中的数据.我就是在文件中找到块,并阅读zTXt的关键字.我在阅读zTXt的压缩部分时遇到问题.我之前从未使用过DeflateStream对象
块的格式是ID(“zTXt”)的4个字节,数据长度的大端32位int,数据,最后是CRC32校验和,我现在忽略它.
zTXt块的格式首先是以null结尾(字符串作为关键字),然后是压缩方法的一个字节(总是0,DEFLATE方法),其余数据是压缩文本.
我的方法接受一个新的FileStream,并返回一个包含zTXt关键字和数据的字典.
这是现在的怪物:
public static List<KeyValuePair<string, string>> GetZtxt(FileStream stream)
{
var ret = new List<KeyValuePair<string, string>>();
try {
stream.Position = 0;
var br = new BinaryReader(stream, Encoding.ASCII);
var head = br.ReadBytes(8); // The header is the same for all PNGs.
if (!head.SequenceEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A })) return null; // Not a PNG.
while (stream.Position < stream.Length) {
int len; // Length of chunk data.
if (BitConverter.IsLittleEndian)
len = BitConverter.ToInt32(br.ReadBytes(4).Reverse().ToArray(), 0);
else
len = br.ReadInt32();
char[] cName = br.ReadChars(4); // The chunk type.
if (cName.SequenceEqual(new[] { 'z', 'T', 'X', 't' })) {
var sb = new StringBuilder(); // Builds the null-terminated keyword associated with the chunk.
char c = br.ReadChar();
do {
sb.Append(c);
c = br.ReadChar();
}
while (c != '\0');
byte method = br.ReadByte(); // The compression method. Should always be 0. (DEFLATE method.)
if (method != 0) {
stream.Seek(len - sb.Length + 3, SeekOrigin.Current); // If not 0, skip the rest of the chunk.
continue;
}
var data = br.ReadBytes(len - sb.Length - 1); // Rest of the chunk data...
var ms = new MemoryStream(data, 0, data.Length); // ...in a MemoryStream...
var ds = new DeflateStream(ms, CompressionMode.Decompress); // ...read by a DeflateStream...
var sr = new StreamReader(ds); // ... and a StreamReader. Yeesh.
var str = sr.ReadToEnd(); // !!! InvalidDataException !!!
ret.Add(new KeyValuePair<string, string>(sb.ToString(), str));
stream.Seek(4, SeekOrigin.Current); // Skip the CRC check.
}
else {
stream.Seek(len + 4, SeekOrigin.Current); // Skip the rest of the chunk.
}
}
}
catch (IOException) { }
catch (InvalidDataException) { }
catch (ArgumentOutOfRangeException) { }
return ret;
}
一旦解决了这个问题,我就需要编写一个将这些zTXt块添加到文件中的函数.所以希望我能理解一旦解决了DeflateStream的工作原理.
非常感谢!!
经过这么久,我终于找到了问题所在.数据采用zlib格式,与仅使用DEFLATE相比,它存储的数据更多一些.如果我在获取压缩数据之前只读取了2个额外字节,则可以正确读取文件.见this feedback page.(我没有提交那个.)
我现在在想.这两个字节的值分别为0x78和0x9C.如果我发现除了那些以外的值,我应该假设DEFLATE会失败吗?
