检测目标C中的PNG文件是否已损坏 [英] Detect if PNG file is corrupted in Objective C

查看:189
本文介绍了检测目标C中的PNG文件是否已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSURLRequest下载jpg和png.这样可以正常工作,但有时文件已损坏. 我已经看到>捕获错误:JPEG数据已损坏:提前结束数据段,并将其用于jpg. 有谁知道对png进行相同操作的方法?即以编程方式检查png数据是否有效...

I'm downloading jpgs and pngs using NSURLRequest. This works ok but sometimes the files are corrupted. I have seen Catching error: Corrupt JPEG data: premature end of data segment and have this working for jpgs. Does anyone know of a way to do the same for pngs? ie Programatically check if the png data is valid...

推荐答案

PNG格式具有多种内置检查功能.每个块"都有CRC32检查,但是要检查您是否需要读取完整文件.

The PNG format has several built in checks. Each "chunk" has a CRC32 check, but to check that you'd need to read the full file.

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

A more basic check (not foolproof, of course) would be to read the start and ending of the file.

前8个字节应始终为以下(十进制)值{ 137, 80, 78, 71, 13, 10, 26, 10 }( ref ).特别是,第二到第四字节对应于ASCII字符串"PNG".

The first 8 bytes should always be the following (decimal) values { 137, 80, 78, 71, 13, 10, 26, 10 } (ref). In particular, the bytes second-to-fourth correspond to the ASCII string "PNG".

以十六进制表示:

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

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

You can also check the last 12 bytes of the file (IEND chunk). The middle 4 bytes should correspond to the ASCII string "IEND". More specifically the last 12 bytes should be (in hexa):

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

(严格来说,PNG文件以这12个字节结尾并不是真正的强制性要求,IEND块本身表示PNG流的结尾,因此,文件在原则上可以具有多余的尾随字节,而这些尾随字节将被PNG流忽略. PNG阅读器.实际上,这是极不可能的.

(Strictly speaking, it's not really obligatory for a PNG file to end with those 12 bytes, the IEND chunk itself signals the end of the PNG stream and so a file could in principle have extra trailing bytes which would be ignored by the PNG reader. In practice, this is extremely improbable).

这篇关于检测目标C中的PNG文件是否已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆