How to check if downloaded PNG image is corrupt?

2019-04-13 08:54发布

I am downloading multiple images from below code and saving to the DB. But for some images I am getting below error.

Error: ImageIO: PNG invalid distance too far back Error: ImageIO: PNG incorrect data check

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

How to check stored image is valid or not, so I can download image again?

1条回答
你好瞎i
2楼-- · 2019-04-13 09:18

For PNG images, check their first two bytes and last two bytes. Below is the method, hope it helps.

Thanks. :)

- (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;
}
查看更多
登录 后发表回答