Catching error: Corrupt JPEG data: premature end of data segment

In response to Slee’s question above, this is the method I use:

-(BOOL)dataIsValidJPEG:(NSData *)data
{
    if (!data || data.length < 2) return NO;

    NSInteger totalBytes = data.length;
    const char *bytes = (const char*)[data bytes];

    return (bytes[0] == (char)0xff && 
            bytes[1] == (char)0xd8 &&
            bytes[totalBytes-2] == (char)0xff &&
            bytes[totalBytes-1] == (char)0xd9);
}

Leave a Comment