Question

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?

Was it helpful?

Solution

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

OTHER TIPS

The accepted answer by swati sharma works great. Here’s a Swift extension for anyone looking to do the same in 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
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top