Topics

#115: Generating Thumbnails from Videos 📼

Topics

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

Then we just create a new CMTime that describes at which point in the video we'd like to capture a thumbnail image. (We use 1/3 of the way through here. Finally, we'll kick off the actual thumbnail generation process and wait for it to complete. We only requested a single frame here, but we can ask for as many as our app needs. The closure will be called once per generated thumbnail.