Objective-C:使用NSData从电影中获取PNG缩略图

我有以下代码尝试从NSData获取video文件的屏幕截图。 我可以确认NSData是有效的而不是nil,但dataString和movieURL都返回nil。

- (UIImage *)imageFromMovie:(NSData *)movieData { // set up the movie player NSString *dataString = [[NSString alloc] initWithData:movieData encoding:NSUTF8StringEncoding]; NSURL *movieURL = [NSURL URLWithString:dataString]; // get the thumbnail AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:movieURL options:nil]; AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1]; generate1.appliesPreferredTrackTransform = YES; NSError *err = NULL; CMTime time = CMTimeMake(1, 2); CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err]; UIImage *one = [[UIImage alloc] initWithCGImage:oneRef]; return(one); } 

编辑:这里看看我从UIImagePicker获取NSData的位置和方式

 if ([mediaType isEqualToString:@"ALAssetTypeVideo"]) { ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init]; [assetLibrary assetForURL:[[info objectAtIndex:x] valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) { ALAssetRepresentation *rep = [asset defaultRepresentation]; unsigned long DataSize = (unsigned long)[rep size]; Byte *buffer = (Byte*)malloc(DataSize); NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:DataSize error:nil]; //here's the NSData NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; } failureBlock:^(NSError *err) { NSLog(@"Error: %@",[err localizedDescription]); }]; } 

可能,你有编码问题。

NSString实例方法-(id)initWithData:data:encoding如果数据不代表有效的编码数据则返回nil。( https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class /#// apple_ref / occ / instm / NSString / initWithData:encoding 🙂

尝试在-(id)initWithData:data:encoding方法中使用正确的编码。

您正在尝试将电影数据转换为NSURL ,这就是您获取nil url的原因。

在您的实现中,您可以通过以下方式获取缩略图:

 AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:[[info objectAtIndex:x] valueForKey:UIImagePickerControllerReferenceURL] options:nil]; AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1]; generate1.appliesPreferredTrackTransform = YES; NSError *err = NULL; CMTime time = CMTimeMake(1, 2); CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err]; UIImage *one = [[UIImage alloc] initWithCGImage:oneRef]; 

在阅读以下答案之前下载我的示例项目:

https://drive.google.com/open?id=0B_exgT43OZJOWl9HMDJCR0cyTW8

我知道你发布这个问题已经很久了; 但是,我发现它,可以回答它,而且我有理由相信,除非你使用Apple Developer Connection网站提供的样本代码来做你所要求的,你仍然需要回答。 我完全基于这个事实:很难弄明白。

尽管如此,我还有一个基本的,有效的项目来解决你的问题; 但是,在查看之前,请查看我在iPhone 6s Plus上运行的video: