如何在iOS中从ALAsset获取视频的缩略图? [英] How to get thumbnail image of video from ALAsset in iOS?

查看:234
本文介绍了如何在iOS中从ALAsset获取视频的缩略图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从视频中获取每一帧的缩略图,然后将这些图像保存在可变图像阵列中。

I want to get thumbnail images of every frame from video and then save this images in Mutable Array of images.

我想用这些图像作为动画。

I want to use this images to play as a animation.

NSURL* assetURL = [self.asset valueForProperty:ALAssetPropertyAssetURL];
NSDictionary* assetOptions = nil;

AVAsset* myAsset = [[AVURLAsset alloc] initWithURL:assetURL options:assetOptions];

self.imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:myAsset];


int duration = CMTimeGetSeconds([myAsset duration]);

for(int i = 0; i<duration; i++)
{
    CGImageRef imgRef = [self.imageGenerator copyCGImageAtTime:CMTimeMake(i, duration) actualTime:NULL error:nil];
    UIImage* thumbnail = [[UIImage alloc] initWithCGImage:imgRef scale:UIViewContentModeScaleAspectFit orientation:UIImageOrientationUp];
    [thumbnailImages addObject:thumbnail];
}

我使用上面的代码来获取缩略图,但问题是,如果有一个2秒的视频我只得到2个缩略图,但我想要20个缩略图(每秒10个缩略图)。

I am using above code to get thumbnail images but the problem is if there is a 2 seconds video i am only getting 2 thumbnails but i want 20 thumbnails (10 thumbnail per second).

那么,如何使用CMTimeMake获取每1秒的缩略图

So, how to use CMTimeMake to get thumbnails for every .1 second

推荐答案

代码表参考站点: 缩略图来自视频的图片

Code form reference site : Thumbnail image from Video

目标 - C

-(UIImage *)generateThumbImage : (NSString *)filepath
{
    NSURL *url = [NSURL fileURLWithPath:filepath];

    AVAsset *asset = [AVAsset assetWithURL:url];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
self.imageGenerator.appliesPreferredTrackTransform = YES; 
        CMTime time = [asset duration];
        time.value = 0;
        Float duration = CMTimeGetSeconds([myAsset duration]);
   for(Float i = 0.0; i<duration; i=i+0.1)
    {
     CGImageRef imgRef = [self.imageGenerator copyCGImageAtTime:CMTimeMake(i, duration) actualTime:NULL error:nil];
     UIImage* thumbnail = [[UIImage alloc] initWithCGImage:imgRef scale:UIViewContentModeScaleAspectFit orientation:UIImageOrientationUp];
    [thumbnailImages addObject:thumbnail];
    }
}

Swift

func generateThumbImage(url : NSURL) -> UIImage{
        var asset : AVAsset = AVAsset.assetWithURL(url) as! AVAsset
        var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true
        var error       : NSError? = nil
        var time        : CMTime = CMTimeMake(1, 30)
        var img         : CGImageRef = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: &error)
        var frameImg    : UIImage = UIImage(CGImage: img)!

        return frameImg
    }

这篇关于如何在iOS中从ALAsset获取视频的缩略图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆