iOS - How to get thumbnail from video without play?

后端 未结 8 1141
鱼传尺愫
鱼传尺愫 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:48

    Please check the link for "Generating Thumbnails from Videos"

    https://littlebitesofcocoa.com/115-generating-thumbnails-from-videos

    It's quite common for an app to need to display one or more thumbnails (small still-image previews) of what's in a video. However, depending on where the video is coming from, we might not have easy access to pre-made thumbnail(s) for it. Let's look at how we can use AVAssetImageGenerator to grab our own. We start with a simple NSURL for the video, this can be local or remote. We'll create an AVAsset with it and that to a new AVAssetImageGenerator object. We'll configure the generator to apply preferred transforms so our thumbnails are in the correct orientation.

    import AVFoundation
    
    if let asset = AVAsset(URL: videoURL) {
       let durationSeconds = CMTimeGetSeconds(asset.duration)
       let generator = AVAssetImageGenerator(asset: asset)
    
       generator.appliesPreferredTrackTransform = true
    
       let time = CMTimeMakeWithSeconds(durationSeconds/3.0, 600)
       var thumbnailImage: CGImageRef 
       generator.generateCGImagesAsynchronouslyForTimes([NSValue(CMTime: time)]) { 
           (requestedTime: CMTime, thumbnail: CGImage?, actualTime: CMTime, result: AVAssetImageGeneratorResult, error: NSError?) in
          self.videoThumbnailImageView.image = UIImage(CGImage: thumbnail)
        }
    }
    

提交回复
热议问题