jmosesman
jmosesman

Reputation: 726

ImageIO: <ERROR> JPEG Corrupt JPEG data: premature end of data segment iphone - how to catch this?

I get this error by downloading an image by HTTP. I have looked at the answer here but even the valid images don't return YES from the function.

Any other ideas?

The code to get the image is simple enough. This happens in a background thread.

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage *image = [UIImage imageWithData:data];

This is the function from that thread:

- (BOOL)isJPEGValid:(NSData *)jpeg {
    if ([jpeg length] < 4) return NO;
    const char * bytes = (const char *)[jpeg bytes];
    if (bytes[0] != 0xFF || bytes[1] != 0xD8) return NO;
    if (bytes[[jpeg length] - 2] != 0xFF || 
            bytes[[jpeg length] - 1] != 0xD9) return NO;
    return YES;
}

Upvotes: 9

Views: 9626

Answers (1)

Sigi
Sigi

Reputation: 260

Use an unsigned char. Then comparing should work.

const unsigned char * bytes = (const unsigned char *)[jpeg bytes];

instead of

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

Upvotes: 13

Related Questions