iOS - How to get thumbnail from video without play?

TienLe picture TienLe · Sep 21, 2015 · Viewed 19.7k times · Source

I'm trying to get thumbnail from video and show it in my tableview. Here is my code:

- (UIImage *)imageFromVideoURL:(NSURL *)contentURL {
    AVAsset *asset = [AVAsset assetWithURL:contentURL];

    //  Get thumbnail at the very start of the video
    CMTime thumbnailTime = [asset duration];
    thumbnailTime.value = 25;

    //  Get image from the video at the given time
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];

    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:thumbnailTime actualTime:NULL error:NULL];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return thumbnail;
}

But image allways return black. What's wrong?

Answer

Ankit Kumar Gupta picture Ankit Kumar Gupta · Mar 24, 2017

Use this : Swift 3 -

func createThumbnailOfVideoFromFileURL(videoURL: String) -> UIImage? {
    let asset = AVAsset(url: URL(string: videoURL)!)
    let assetImgGenerate = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    let time = CMTimeMakeWithSeconds(Float64(1), 100)
    do {
        let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        let thumbnail = UIImage(cgImage: img)
        return thumbnail
    } catch {
        return UIImage(named: "ico_placeholder")
    }
}

Important Note :

You will need to use this in an if else as it is resource extensive. You will have to store the image in an array or model and check that if once thumbnail has been created it refers to the cache/array so that cellForRowAtIndexPath does not cause a lag in scrolling your UITableView