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

jmosesman picture jmosesman · Feb 13, 2012 · Viewed 9.3k times · Source

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

Answer

Sigi picture Sigi · Apr 3, 2012

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