我正试图从UIImagePickerController
中的所选视频中获取第一帧以显示UIImageView
,但我不知道是否可能。如果是的话,我该怎么做?
答案 0 :(得分:28)
您可以通过以下两种方式之一完成此操作。第一种方法是使用MPMoviePlayerController
来抓取缩略图:
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:videoURL];
moviePlayer.shouldAutoplay = NO;
UIImage *thumbnail = [moviePlayer thumbnailImageAtTime:time
timeOption:MPMovieTimeOptionNearestKeyFrame];
这样可行,但MPMoviePlayerController
不是特别轻量级的对象,也不是特别快速抓取缩略图。
首选方法是在AVFoundation中使用新的AVAssetImageGenerator
。这比旧方式快速,轻便且灵活。这是一个帮助方法,它将从视频中返回一个自动释放的图像。
+ (UIImage *)thumbnailImageForVideo:(NSURL *)videoURL
atTime:(NSTimeInterval)time
{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetIG =
[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetIG.appliesPreferredTrackTransform = YES;
assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError *igError = nil;
thumbnailImageRef =
[assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)
actualTime:NULL
error:&igError];
if (!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@", igError );
UIImage *thumbnailImage = thumbnailImageRef
? [[UIImage alloc] initWithCGImage:thumbnailImageRef]
: nil;
return thumbnailImage;
}
异步使用
- (void)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time completion:(void (^)(UIImage *)) completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetIG =
[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetIG.appliesPreferredTrackTransform = YES;
assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError *igError = nil;
thumbnailImageRef =
[assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)
actualTime:NULL
error:&igError];
if (!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@", igError );
UIImage *thumbnailImage = thumbnailImageRef
? [[UIImage alloc] initWithCGImage:thumbnailImageRef]
: nil;
dispatch_async(dispatch_get_main_queue(), ^{
completion(thumbnailImage);
});
});
}