如何检查下载的PNG图像是否已损坏?

时间:2012-10-31 06:46:34

标签: iphone objective-c xcode png corrupt

我从下面的代码下载多个图像并保存到数据库。但对于某些图像,我的误差低于此值。

错误:ImageIO:PNG无效距离太远 错误:ImageIO:PNG错误数据检查

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);                               
dispatch_async(queue, ^{
    NSString *imgStr = [dict  objectForKey:@"image"];                  
    imgStr = [imgStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgStr]];
    UIImage *image = [UIImage imageWithData:imgData];

    dispatch_sync(dispatch_get_main_queue(), ^{
       mYImageView.image = image;
    });
});

enter image description here

如何检查存储的图像是否有效,我可以再次下载图像吗?

2 个答案:

答案 0 :(得分:7)

对于PNG图像,请检查它们的前两个字节和最后两个字节。下面是方法,希望它有所帮助。

感谢。 :)

- (BOOL)isImageValid:(NSData *)data
{
    BOOL val = YES;

    if ([data length] < 4) 
        val = NO;

    const char * bytes = (const char *)[data bytes];

    if (bytes[0] != 0x89 || bytes[1] != 0x50) 
        val = NO;
    if (bytes[[data length] - 2] != 0x60 || 
        bytes[[data length] - 1] != 0x82) 
        val = NO;

    return val;
}

答案 1 :(得分:0)

accepted answer by swati sharma 效果很好。这是一个 Swift 扩展,适用于希望在 Swift 中执行相同操作的任何人:

extension Data
{
    /// Returns whether or not the data is for a valid PNG file.
    var isValidPNG: Bool
    {
        guard self.count > 4 else { return false }
        
        return self[0] == 0x89 &&
            self[1] == 0x50 &&
            self[self.count - 2] == 0x60 &&
            self[self.count - 1] == 0x82
    }
}