OC学习06:截取视频文件第一帧的方法有哪些?

张建 lol

前言

iOS 中获取视频第一帧有两种方式

第一种:使用AVFoundation获取

将耗时的操作放在异步执行队列 dispatch_async,防止造成线程堵塞,刷新UI放在 主线程

1
2
3
4
5
6
7
8
9
10
11
12
- (UIImage *)getFirstFrameFromVideoWithUrl:(NSURL *)url{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *assetGennerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetGennerator.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
CMTime actualTime;
NSError *error = nil;
CGImageRef image = [assetGennerator copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *videoImg = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return videoImg;
}

第二种方式:使用SDWebImage获取,并缓存图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
- (void)method2{
NSURL *url = [NSURL URLWithString:@"https://klxxcdn.oss-cn-hangzhou.aliyuncs.com/histudy/hrm/media/bg1.mp4"];
NSString *urlKey = url.absoluteString;
// 先从缓存中查找是否有图片
SDImageCache *imgCache = [SDImageCache sharedImageCache];
UIImage *memoryImg = [imgCache imageFromCacheForKey:urlKey];
if (memoryImg) {
self.imgV.image = memoryImg;
}else {
// 从磁盘中查找是否有图片
UIImage *diskImg = [imgCache imageFromDiskCacheForKey:urlKey];
if (diskImg) {
self.imgV.image = diskImg;
}else { // 如果都不存在
// 开启异步线程下载图片
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetGenerator.appliesPreferredTrackTransform = YES;
assetGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbImgRef = NULL;
CFTimeInterval thumbImgTime = 1;
NSError *thumbImgError = nil;
thumbImgRef = [assetGenerator copyCGImageAtTime:CMTimeMake(thumbImgTime, 60) actualTime:NULL error:&thumbImgError];
if (!thumbImgRef){
NSLog(@"thumbImgError:%@",thumbImgError);
}
UIImage *thumbImg = thumbImgRef ? [[UIImage alloc] initWithCGImage:thumbImgRef] : nil;
// 主线程显示UI
dispatch_async(dispatch_get_main_queue(), ^{
SDImageCache *imgCache = [SDImageCache sharedImageCache];
[imgCache storeImage:thumbImg forKey:urlKey completion:^{
NSLog(@"store Image success");
}];
self.imgV.image = thumbImg;
});
});
}
}

}
  • Post title:OC学习06:截取视频文件第一帧的方法有哪些?
  • Post author:张建
  • Create time:2023-03-07 19:16:39
  • Post link:https://redefine.ohevan.com/2023/03/07/OC/OC学习06:截取视频文件第一帧的方法有哪些?/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
On this page
OC学习06:截取视频文件第一帧的方法有哪些?