Skip to content

Getting a Thumbnail with AVAssetImageGenerator

AVAssetImageGenerator, Swift, iOS1 min read

As developers, we often encounter scenarios where we need to work with multimedia assets in our applications. Whether it's for creating custom video players, building media editing tools, or simply to provide users with a preview of the content they are about to play, being able to extract thumbnail images from videos is an essential feature. In this article, we'll explore how to achieve this using AVAssetImageGenerator, a powerful class provided by Apple's AVFoundation framework.

What is AVAssetImageGenerator?

AVAssetImageGenerator is a class within the AVFoundation framework, which provides a suite of high-level interfaces for working with time-based audiovisual media on Apple platforms. Specifically, AVAssetImageGenerator allows us to generate thumbnail images at specific times from a given video asset. This class makes it straightforward to obtain single or multiple frames as UIImage objects, providing us with the flexibility to utilize them within our applications.

Using AVAssetImageGenerator

To start using AVAssetImageGenerator, we first need to import AVFoundation into our project. Once imported, we can begin by creating an instance of AVURLAsset, representing the video file for which we want to extract a thumbnail.

1import AVFoundation
3let videoURL = URL(fileURLWithPath: "path_to_your_video_file")
4let asset = AVAsset(url: videoURL)
5let imageGenerator = AVAssetImageGenerator(asset: asset)

Next, we define the time within the video from which we'd like to capture a thumbnail. This could be at a specific point, such as the start of the video, or dynamically determined based on user interaction or other factors in our application.

1let time = CMTimeMake(value: 1, timescale: 60) // Capture frame at 1 second

With the time defined, we can now create the actual thumbnail:

1do {
2 let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
3 let thumbnail = UIImage(cgImage: cgImage)
4 // Use the 'thumbnail' UIImage as needed
5} catch let error {
6 print("Error generating thumbnail: \(error.localizedDescription)")

By utilizing the copyCGImage(at:actualTime:) method, we obtain a CGImage representation of the video frame at the specified time. We then convert this into a UIImage, ready to be integrated into our user interface or processed further according to our application's requirements.

Fine-tuning Thumbnail Generation

AVAssetImageGenerator provides further options for refining the extraction process, such as specifying the maximum dimensions for the generated images, enabling or disabling aspect ratio preservation, and setting the aperture mode for handling non-square pixel formats. These options enable us to tailor the output to suit our specific use case, ensuring that the extracted thumbnails align with our application's design and performance expectations.