UIImageView显示视频第一帧图片
引入头文件
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVTime.h>
// 获取视频第一帧图片(异步加载数据)
-(void)getVideoPreViewImageURL:(NSURL *)path forImageView:(UIImageView *)imageView placeHolderImage:(UIImage *)placeHolder
{
// 视频链接转MD5作为图片的名字
NSString *name = [[path absoluteString] ms_MD5String];
NSString *PATH = [NSString stringWithFormat:@"%@/Documents/videoFolder/%@.png",NSHomeDirectory(),name];
UIImage *imagePath = [[UIImage alloc] initWithContentsOfFile:PATH];
if (imagePath) {
// 本地有缓存图片,加载本地图片并return
imageView.image = imagePath;
return;
}else{
// 本地没有缓存图片,先加载占位图
imageView.image = placeHolder;
}
dispatch_group_t group = dispatch_group_create();
__block UIImage *videoImage;
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetGen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 2);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
videoImage = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
// 创建文件夹
NSString *folder = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/videoFolder"];
[[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:nil];
[UIImagePNGRepresentation(videoImage) writeToFile:PATH atomically:YES];
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 主线程更新UI
imageView.image = videoImage;
});
}