iOS-如何在不播放的情况下从视频获取缩略图? [英] iOS - How to get thumbnail from video without play?

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

问题描述

我正在尝试从视频中获取缩略图,并将其显示在我的表格视图中.这是我的代码:

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?

推荐答案

使用此方法: 雨燕3-

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")
    }
}

重要提示:

如果资源丰富,则需要在其他情况下使用它.您将必须将图像存储在数组或模型中,并检查是否一旦创建了缩略图就引用了缓存/数组,以使cellForRowAtIndexPath不会导致滚动UITableView

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

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

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