问题
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