iOS下载png损坏如何检测或避免
大家讲道理
大家讲道理 2017-04-17 13:14:24
[iOS讨论组]

经常在网络不太好时下载的png图片会出现模糊或者不完整现象,如何在ios开发里避免活着检测出图片已经损坏呢?如下图:

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
PHP中文网

我读了下MKNetworkKit源码和要求,发现使用到了ImageIO.framework,这个框架应该对图像数据做了序列处理,不然就可能出现数据混乱。现在在网络极差的情况下也暂时没有发现这种情况。

2014年11月26日补充:
我发现引入ImageIO后,图片仍然有时候会损坏。在我就快要放弃了的时候,真是功夫不负有心人,在各种stackoverflow和google无解之后,我自己读了UIImage、UIImageView以及ImageIO的源码和官方说明,找到了个取巧的办法,你需要写下面两步代码:

1.读取图片数据,然后调用2中的方法进行校验

NSData* data = [NSData dataWithContentsOfFile:imagePath];

2.判断是否为有效的PNG图片,JPG的请使用UIImageJPEGRepresentation方法

/**
 *  校验图片是否为有效的PNG图片
 *
 *  @param imageData 图片文件直接得到的NSData对象
 *
 *  @return 是否为有效的PNG图片
 */
- (BOOL)isValidPNGByImageData:(NSData*)imageData
{
    UIImage* image = [UIImage imageWithData:imageData];
    //第一种情况:通过[UIImage imageWithData:data];直接生成图片时,如果image为nil,那么imageData一定是无效的
    if (image == nil && imageData != nil) {

        return NO;
    }

    //第二种情况:图片有部分是OK的,但是有部分坏掉了,它将通过第一步校验,那么就要用下面这个方法了。将图片转换成PNG的数据,如果PNG数据能正确生成,那么这个图片就是完整OK的,如果不能,那么说明图片有损坏
    NSData* tempData = UIImagePNGRepresentation(image);
    if (tempData == nil) {
        return NO;
    } else {
        return YES;
    }
}

真是眼泪都留下来了!~

大家讲道理

引用自http://www.w3.org/TR/PNG/

PNG的每个数据块都保有CRC位以供检验,算法是:

x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1

In PNG, the 32-bit CRC is initialized to all 1's, and then the data from each byte is processed from the least significant bit (1) to the most significant bit (128). After all the data bytes are processed, the CRC is inverted (its ones complement is taken). This value is transmitted (stored in the datastream) MSB first. For the purpose of separating into bytes and ordering, the least significant bit of the 32-bit CRC is defined to be the coefficient of the x31 term.
Practical calculation of the CRC often employs a precalculated table to accelerate the computation http://www.w3.org/TR/PNG-CRCAppendix.html

当然,还是得看图片源靠谱不靠谱,如果图片源偷懒,CRC位全部置1就没辙了=w=。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号