iOS--获取视频截图&缩略图
define k_THUMBNAIL_IMG_WIDTH 100//缩略图大小
define k_FPS 1//一秒想取多少帧
//这本来是个异步调用,但写成这种方便大家看和复制来直接测试
-
(UIImage)getVideoThumbnailWithUrl:(NSURL)videoUrl second:(CGFloat)second
{
if (!videoUrl)
{
NSLog(@"WARNING:videoUrl为空");
return nil;
}
AVURLAsset *urlSet = [AVURLAsset assetWithURL:videoUrl];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
imageGenerator.appliesPreferredTrackTransform = YES;
imageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;/*
如果不需要获取缩略图,就设置为NO,如果需要获取缩略图,则maximumSize为获取的最大尺寸。
以BBC为例,getThumbnail = NO时,打印宽高数据为:19201072。
getThumbnail = YES时,maximumSize为100100。打印宽高数据为:10055.
注:不乘[UIScreen mainScreen].scale,会发现缩略图在100100很虚。
*/
BOOL getThumbnail = YES;
if (getThumbnail)
{
CGFloat width = [UIScreen mainScreen].scale * k_THUMBNAIL_IMG_WIDTH;
imageGenerator.maximumSize = CGSizeMake(width, width);
}
NSError *error = nil;
CMTime time = CMTimeMake(second,k_FPS);
CMTime actucalTime;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
if (error) {
NSLog(@"ERROR:获取视频图片失败,%@",error.domain);
}
CMTimeShow(actucalTime);
UIImage *image = [UIImage imageWithCGImage:cgImage];
NSLog(@"imageWidth=%f,imageHeight=%f",image.size.width,image.size.height);
CGImageRelease(cgImage);
return image;
}
原文链接:https://www.jianshu.com/p/943a1f03ec00
CMTime CMTimeMake (
int64_t value, //表示 当前视频播放到的第几桢数
int32_t timescale //每秒的帧数
);