How to extract a UIImage from a video in iOS 9

Here are two ways to extract the first frame of vision and turn it into a UIImage. Both methods are from the generous Stack Overflow community.

Both methods make use to the AV Foundation framework. There’s no need to import it, UIKit will take care of it for us.

Video URLs can be obtained in many ways, one of which is from something like an image picker. You can grab the URL in its didFinishPickingMediaWithInfo delegate method:

Now that we have a video URL, let’s see how we can extract a UIImage from it.

Method 1: Short and Sweet

Here’s a short and sweet method by nullp0inter. This will extract the first frame of the video:

This creates an image generator from an asset, from which we can extract a CGImage near an iframe of the video. We’ll create our own time using CMTimeMake, setting it to the very beginning here.

Then we’ll turn the CGImage into a more usable UIImage. Setting the appliesPreferredTrackTransform property to YES guarantees that the image is returned the correct way up, rather than rotated (which otherwise happens sometimes).


Method 2: Complex and Elaborate

Another way to extract a UIImage comes courtesy of memmons. The principle is the same as above, with additional error checks in place, and the option to specify an NSTimeInterval at which the image should be returned:

Further Reading

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.