#import "RootViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
// 记得导入上面三个框架
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView * imagev = [[UIImageView alloc] initWithFrame:(CGRectMake(50, 50, 200, 150))];
imagev.image = [self imageWithMediaURL:[NSURL URLWithString:@"http://视频的网址.mp4"]];
imagev.backgroundColor = [UIColor redColor];
[self.view addSubview:imagev];
}
/**
* 通过视频的URL,获得视频缩略图
*
* @param url 视频URL
*
* @return首帧缩略图
*/
- (UIImage *)imageWithMediaURL:(NSURL *)url {
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
// 初始化媒体文件
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
// 根据asset构造一张图
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
// 设定缩略图的方向
// 如果不设定,可能会在视频旋转90/180/270°时,获取到的缩略图是被旋转过的,而不是正向的(自己的理解)
generator.appliesPreferredTrackTransform = YES;
// 设置图片的最大size(分辨率)
generator.maximumSize = CGSizeMake(600, 450);
// 初始化error
NSError *error = nil;
// 根据时间,获得第N帧的图片
// CMTimeMake(a, b)可以理解为获得第a/b秒的frame
CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10000) actualTime:NULL error:&error];
// 构造图片
UIImage *image = [UIImage imageWithCGImage: img];
return image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
获取视频首张缩略图全部详细代码
最新推荐文章于 2023-11-14 14:18:42 发布