Lalit Kumar Lalit Kumar - 6 months ago 233
iOS Question

How to get thumbnail image of video from ALAsset in iOS?

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];
}


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).

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

Answer

Objective - 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
    }
Comments