问题描述
我有一个基于RTSP / UDP的MJPEG流我想从中使用[UIImage initWithData:]为UIImageView生成JPEG。大部分时间这都很好,但有时我会得到损坏的图像和日志消息,如:
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 corrupt images and log messages like:
ImageIO: <ERROR> JPEGCorrupt JPEG data: premature end of data segment
我的问题是:我怎么看(在运行时) ,这样的消息发生了吗?不幸的是'initWithData'没有错误输出,还有其他方法吗?
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确实返回一个有效的UIImage对象,而不是nil!
in this case, the initWithData does return a valid UIImage object, not nil!
推荐答案
这个上有一个类似的线程堆栈溢出:。
There is a similar thread to this one on stack overflow: Catching error: Corrupt JPEG data: premature end of data segment.
解决方案是检查标头字节 FF D8
和结束字节 FF D9
。因此,如果您在NSData中有图像数据,则可以这样检查:
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;
}
然后,要检查JPEG数据是否无效,只需写:
Then, to check if JPEG data is invalid, just write:
if (![self isJPEGValid:myData]) {
NSLog(@"Do something here");
}
希望这会有所帮助!
这篇关于如何在[UIImage initWithData:]中获取错误/警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!