获取视频的第一针图片(加载和下载图片)是耗时操作,会阻塞线程,在这里使用队列处理,当下载或加载图片完成后回到主线程更新UI。
建议创建UIImageView的分类,我这里就简单书写了一下大概的实现方法。
首先导入头文件
///获取视频的图片
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
//获取视频第一帧图片优化(异步加载数据)
-(void)getVideoPreViewImageURL:(NSURL *)path forImageView:(UIImageView *)imageView placeHolderImage:(UIImage *)placeHolder
{
NSString *name = [[path absoluteString] wl_toMD5];//视频链接转MD5作为图片的名字
//NSString *name = [path absoluteString];
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;
});
}