How to get errors/warnings in [UIImage initWithData:]

后端 未结 3 923
情歌与酒
情歌与酒 2021-01-21 07:04

i have an MJPEG stream over RTSP/UDP from which i want to generate JPEGs for a UIImageView with [UIImage initWithData:]. Most of the time this works good, but sometimes i get co

3条回答
  •  梦毁少年i
    2021-01-21 07:41

    There is a similar thread to this one on stack overflow: Catching error: Corrupt JPEG data: premature end of data segment.

    There solution is to check for the header bytes FF D8 and ending bytes FF D9. So, if you have image data in an NSData, you can check it like so:

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

    Then, to check if JPEG data is invalid, just write:

    if (![self isJPEGValid:myData]) {
        NSLog(@"Do something here");
    }
    

    Hope this helps!

提交回复
热议问题