How to check if downloaded PNG image is corrupt?

廉价感情. 提交于 2019-12-14 00:24:47

问题


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;
    });
});

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


回答1:


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;
}


来源:https://stackoverflow.com/questions/13152616/how-to-check-if-downloaded-png-image-is-corrupt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!