iOS - How to get thumbnail from video without play?

后端 未结 8 1121
鱼传尺愫
鱼传尺愫 2020-12-16 00:36

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

- (UIImage *)imageFromVideoURL:(NSURL *)contentURL {
    AVAsset *asse         


        
相关标签:
8条回答
  • 2020-12-16 00:53

    SWIFT 5.2 VERSION:

    You can find my original post here, where I took inspiration from rozochkin's answer.

    func getCurrentFrame() -> UIImage? {
        guard let player = self.player, let avPlayerAsset = player.currentItem?.asset else {return nil}
        let assetImageGenerator = AVAssetImageGenerator(asset: avPlayerAsset)
        assetImageGenerator.requestedTimeToleranceAfter = .zero
        assetImageGenerator.requestedTimeToleranceBefore = .zero
        assetImageGenerator.appliesPreferredTrackTransform = true
        let imageRef = try! assetImageGenerator.copyCGImage(at: player.currentTime(), actualTime: nil)
        let image = UIImage(cgImage: imageRef)
        return image
    }
    

    IMPORTANT NOTES:

    requestedTimeToleranceAfter and requestedTimeToleranceBefore should be set to .zero, because, according to source code, "The actual time of the generated images [...] may differ from the requested time for efficiency".

    appliesPreferredTrackTransform must be set to TRUE (default is FALSE), otherwise you get a bad-rotated frame. With this property set to TRUE you get what you really see in the player.

    0 讨论(0)
  • 2020-12-16 01:04
    func getThumbnailFrom(path: URL) -> UIImage? {
    
            do {
                let asset = AVURLAsset(url: path , options: nil)
                let imgGenerator = AVAssetImageGenerator(asset: asset)
                imgGenerator.appliesPreferredTrackTransform = true
                let timestamp = asset.duration
                print("Timestemp:   \(timestamp)")
                let cgImage = try imgGenerator.copyCGImage(at: timestamp, actualTime: nil)
                let thumbnail = UIImage(cgImage: cgImage)
                return thumbnail
                } catch let error {
                print("*** Error generating thumbnail: \(error.localizedDescription)")
                return nil
              }
            }
    

    This Code is working.

    0 讨论(0)
提交回复
热议问题