Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 206
jmosesman Avatar asked Feb 13 '12 17:02

jmosesman


1 Answers

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];
like image 93
Sigi Avatar answered Feb 06 '23 22:02

Sigi