简体   繁体   English

如何在 [UIImage initWithData:] 中获取错误/警告

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

i have an MJPEG stream over RTSP/UDP from which i want to generate JPEGs for a UIImageView with [UIImage initWithData:].我有一个基于 RTSP/UDP 的 MJPEG stream,我想从中生成带有 [UIImage initWithData:] 的 UIImageView 的 JPEG。 Most of the time this works good, but sometimes i get corrupt images and log messages like:大多数时候这很好用,但有时我会收到损坏的图像和日志消息,例如:

ImageIO: <ERROR> JPEGCorrupt JPEG data: premature end of data segment

My Question is: how can i see (during runtime), that such message occurs?我的问题是:我如何才能看到(在运行时)出现这样的消息? Unfortunatly 'initWithData' has no error output, is there any other way?不幸的是'initWithData'没有错误output,还有其他方法吗?

Thank you.谢谢你。

Edit: in this case, the initWithData does return a valid UIImage object, not nil!编辑:在这种情况下,initWithData 确实返回一个有效的 UIImage object,而不是零!

The initWithData: method should return nil in such cases.在这种情况下, initWithData:方法应该返回nil

Try:尝试:

UIImage *myImage = [[UIImage alloc] initWithData:imgData];
if(!myImage) {
    // problem
}

There is a similar thread to this one on stack overflow: Catching error: Corrupt JPEG data: premature end of data segment .堆栈溢出有一个与此类似的线程: 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 .解决方案是检查 header 字节FF D8和结束字节FF D9 So, if you have image data in an NSData, you can check it like so:所以,如果你在 NSData 中有图像数据,你可以像这样检查它:

- (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:然后,要检查 JPEG 数据是否无效,只需编写:

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

Hope this helps!希望这可以帮助!

I've encountered the same problem in this exact situation.在这种确切的情况下,我遇到了同样的问题。

It turned out that I was passing an instance of NSMutableData to global queue for decoding.原来,我正在将 NSMutableData 的一个实例传递给全局队列进行解码。 During decoding the data in NSMutableData was overwritten by next frame received from network.在解码期间,NSMutableData 中的数据被从网络接收到的下一帧覆盖。

I've fixed the errors by passing a copy of the data.我通过传递数据的副本修复了错误。 It might be better to use a buffer pool to improve performance:使用缓冲池来提高性能可能会更好:

    NSData *dataCopy = [_receivedData copy];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    ZAssert([self isJPEGValid:dataCopy], @"JPEG data is invalid"); // should never happen
    UIImage *image = [UIImage imageWithData:dataCopy];
    dispatch_async(dispatch_get_main_queue(), ^{
        // show image
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM