Creating Thumbnail for Video in iOS

Creating Thumbnail for Video in iOS

Try this (it doesn't actually show the movie player):

+ (UIImage *)imageFromMovie:(NSURL *)movieURL atTime:(NSTimeInterval)time {
// set up the movie player
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc]
initWithContentURL:movieURL];
mp.shouldAutoplay = NO;
mp.initialPlaybackTime = time;
mp.currentPlaybackTime = time;
// get the thumbnail
UIImage *thumbnail = [mp thumbnailImageAtTime:time
timeOption:MPMovieTimeOptionNearestKeyFrame];
// clean up the movie player
[mp stop];
[mp release];
return(thumbnail);
}

It's supposed to be a synchronous call, so it might block the main thread some, but seems to be running pretty instantly for me when I use a time at the beginning of the movie. If you're doing this a lot, you can add it as a category on UIImage, which is what I did.

I see from your question that you want to do this before the movie is saved, and I guess it might not work without a file url. However, if you're using the UIImagePickerController for camera capture, you can pass this function the URL returned in the info dictionary of imagePickerController:didFinishPickingMediaWithInfo: with the key UIImagePickerControllerMediaURL.

Creating thumbnail from local video in swift

Translated with some edits from:

First frame of a video using AVFoundation

    var err: NSError? = nil
let asset = AVURLAsset(URL: NSURL(fileURLWithPath: "/that/long/path"), options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
let cgImage = imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil, error: &err)
// !! check the error before proceeding
let uiImage = UIImage(CGImage: cgImage)
let imageView = UIImageView(image: uiImage)
// lay out this image view, or if it already exists, set its image property to uiImage

Unable to generate thumbnail from video in gallery

Use UIImagePickerController.InfoKey.mediaURL to key into the info dictionary. UIImagePickerController.InfoKey.referenceURL is deprecated.

func didSelectVideo(at url: URL) {
let asset = AVAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
let cgImage = try! generator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
cell.image.image = thumbnail
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true) {
guard let url = info[.mediaURL] as? URL else { return }
self.didSelectVideo(at: url)
}
}

Generating thumbnail from Video ends up always rotated in an UIImageView

It seems like setting the imageGenerator.appliesPreferredTrackTransform = true solves this issue.



Related Topics



Leave a reply



Submit