ImageIO: JPEG Corrupt JPEG data: premature

2019-02-09 05:29发布

问题:

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

回答1:

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