iOS: Getting a Thumbnail for a Video

smart phone taking a picture
Credit: Pixabay / SplitShire

Between various things being deprecated, and the new Photos framework (which looks cool but seemed a bit heavyweight for this purpose) finding this took me a while!

When the image picker returns with a video it has a url in info[UIImagePickerControllerMediaURL]. Then we can use AVAsset and AVAssetGenerator to get a thumbnail.

// Gets the asset - note ALAsset is deprecated, not AVAsset.
AVAsset *asset = [AVAsset assetWithURL:mediaUrl];

// Calculate a time for the snapshot - I'm using the half way mark.
CMTime duration = [asset duration];
CMTime snapshot = CMTimeMake(duration.value / 2, duration.timescale);

// Create a generator and copy image at the time.
// I'm not capturing the actual time or an error.
AVAssetImageGenerator *generator =
    [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
CGImageRef imageRef = [generator copyCGImageAtTime:snapshot

// Make a UIImage and release the CGImage.
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];

// TODO: Do something with the image!

Also useful when using the simulator: test videos. Download, open on the simulator, and then save via the share button as for images.

This is something I was working on for Digital Fan Clubs.

One reply on “iOS: Getting a Thumbnail for a Video”

Comments are closed.