在Objective C中检测PNG文件是否损坏

4
3个回答

7

PNG格式有几个内置的检查。每个“块”都有一个CRC32检查,但要进行检查,您需要读取完整文件。

更基本的检查(当然不是万无一失)是读取文件的开头和结尾。

前8个字节应始终是以下(十进制)值{ 137, 80, 78, 71, 13, 10, 26, 10 } (参考资料)。特别地,第二到第四个字节对应于ASCII字符串“PNG”。

以十六进制表示:

89 50 4e 47 0d 0a 1a 0a
.. P  N  G  ...........

您还可以检查文件的最后12个字节(IEND块)。中间4个字节应该对应ASCII字符串“IEND”。更具体地说,最后12个字节应为(以十六进制表示):

00 00 00 00 49 45 4e 44 ae 42 60 82
........... I  E  N  D  ...........

严格来说,PNG文件不一定非得以那12个字节结尾,IEND块本身就标志着PNG流的结束,因此理论上一个文件可以有额外的尾随字节,这些字节会被PNG读取器忽略。但在实践中,这是极不可能的。


2

就像在捕获错误:损坏的JPEG数据:数据段过早结束中一样,这里是PNG的代码片段:

- (BOOL)dataIsValidPNG:(NSData *)data
{
    if (!data || data.length < 12)
    {
        return NO;
    }

    NSInteger totalBytes = data.length;
    const char *bytes = (const char *)[data bytes];

    return (bytes[0] == (char)0x89 && // PNG
            bytes[1] == (char)0x50 &&
            bytes[2] == (char)0x4e &&
            bytes[3] == (char)0x47 &&
            bytes[4] == (char)0x0d &&
            bytes[5] == (char)0x0a &&
            bytes[6] == (char)0x1a &&
            bytes[7] == (char)0x0a &&

            bytes[totalBytes - 12] == (char)0x00 && // IEND
            bytes[totalBytes - 11] == (char)0x00 &&
            bytes[totalBytes - 10] == (char)0x00 &&
            bytes[totalBytes - 9] == (char)0x00 &&
            bytes[totalBytes - 8] == (char)0x49 &&
            bytes[totalBytes - 7] == (char)0x45 &&
            bytes[totalBytes - 6] == (char)0x4e &&
            bytes[totalBytes - 5] == (char)0x44 &&
            bytes[totalBytes - 4] == (char)0xae &&
            bytes[totalBytes - 3] == (char)0x42 &&
            bytes[totalBytes - 2] == (char)0x60 &&
            bytes[totalBytes - 1] == (char)0x82);
}

0

dataIsValidPNG的更好版本:

BOOL dataIsValidPNG(NSData *data) {

    if (!data) {
        return NO;
    }

    const NSInteger totalBytes = data.length;
    const char *bytes = (const char *)[data bytes];
    const char start[] = { '\x89',  'P',  'N',  'G', '\r', '\n', '\x1a', '\n' };
    const char end[]   = {   '\0', '\0', '\0', '\0',  'I',  'E',    'N',  'D', '\xAE', 'B', '`', '\x82' };

    if (totalBytes < (sizeof(start) + sizeof(end))) {
        return NO;
    }

    return (memcmp(bytes, start, sizeof(start)) == 0) &&
           (memcmp(bytes + (totalBytes - sizeof(end)), end, sizeof(end)) == 0);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接