---
title: "#115: Generating Thumbnails from Videos 📼"
url: https://littlebitesofcocoa.com/115-generating-thumbnails-from-videos
author: Jake Marsh
date: 2015-10-30
published: 2015-10-30
topics: ["Media"]
description: "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."
---

# #115: Generating Thumbnails from Videos 📼

By Jake Marsh, October 30, 2015. HTML: 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 <i>preferred transforms</i> so our **thumbnails** are in the correct orientation. 

``` swift
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**.
