Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

When creating an UIImage with corrupt/incomplete JPEG data, the console will print out

<Error>: Corrupt JPEG data: premature end of data segment

The incomplete image will be shown, with grey filling up the incomplete part. I do not want this to happen.

I desperately tried with a try-catch block but it does not catch the error. Is there any way to catch the error?

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

Depends on how you are getting the data etc. Maybe this is what you are looking for: iphone-corrupt-jpeg-data-for-image-received-over-http

A simple way to check if the JPEG data is complete or not is to check the first and last two bytes for FF D8 and FF D9 respectively. Those two bytes identify the start and end of a JPEG file respectively.

This would work as a solution for my purpose. But I am still curious how the error can be catch. – samwize Oct 4, 2010 at 1:48 so if I have the JPG represented as NSData from the iOS disk how would I check the last 2 digits? – Slee Jun 12, 2012 at 16:46

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.