从Swift 3.0中的Server Video Url获取Thumbail / Preview图像

时间:2017-02-09 06:35:13

标签: ios swift swift3

我想从服务器上的视频底层获取缩略图图像。视频文件不在本地。它在我的Sever上。视频文件的扩展名为.m3u8。

3 个答案:

答案 0 :(得分:8)

你可以做到。

首先需要导入AVFoundation

    import AVFoundation

然后将下面的代码放到您的控制器上:

func getThumbnailImage(forUrl url: URL) -> UIImage? {
    let asset: AVAsset = AVAsset(url: url)
    let imageGenerator = AVAssetImageGenerator(asset: asset)

    do {
        let thumbnailImage = try imageGenerator.copyCGImage(at: CMTimeMake(1, 60) , actualTime: nil)
        return UIImage(cgImage: thumbnailImage)
    } catch let error {
        print(error)
    }

    return nil
}

用法:

    let imageView = UIImageView()
    let url = URL(string: "https://firebasestorage.googleapis.com/v0/b/shaberi-a249e.appspot.com/o/message-videos%2F8EDAC3FC-D754-4165-990A-97F6ECE120A6.mp4?alt=media&token=b3271370-a408-467d-abbc-7df2beef45c7")

    if let thumbnailImage = getThumbnailImage(forUrl: url) {
        imageView.image = thumbnailImage
    }

网址 更改为您的视频链接。

希望有所帮助!

答案 1 :(得分:0)

在Swift 5.1(也是旧版本)中,您可以这样做:

private func createVideoThumbnail(from url: URL) -> UIImage? {

    let asset = AVAsset(url: url)
    let assetImgGenerate = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.maximumSize = CGSize(width: frame.width, height: frame.height)

    let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600)
    do {
        let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        let thumbnail = UIImage(cgImage: img)
        return thumbnail
    }
    catch {
      print(error.localizedDescription)
      return nil
    }

}

请注意,AVKit需要导入

答案 2 :(得分:0)

第1步

import AVFoundation

第2步

在ViewController中添加以下功能

func getThumbnailImageFromVideoUrl(url: URL, completion: @escaping ((_ image: UIImage?)->Void)) {
    DispatchQueue.global().async { //1
        let asset = AVAsset(url: url) //2
        let avAssetImageGenerator = AVAssetImageGenerator(asset: asset) //3
        avAssetImageGenerator.appliesPreferredTrackTransform = true //4
        let thumnailTime = CMTimeMake(value: 2, timescale: 1) //5
        do {
            let cgThumbImage = try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil) //6
            let thumbNailImage = UIImage(cgImage: cgThumbImage) //7
            DispatchQueue.main.async { //8
                completion(thumbNailImage) //9
            }
        } catch {
            print(error.localizedDescription) //10
            DispatchQueue.main.async {
                completion(nil) //11
            }
        }
    }
}

第3步

self.getThumbnailImageFromVideoUrl(url: videoUrl) { (thumbNailImage) in
    self.yourImageView.image = thumbNailImage
}

如果您需要完整的说明,请参考以下链接 https://www.swiftdevcenter.com/get-thumbnail-from-video-url-in-background-swift/