Display preview image from video clip

I have a folder in the document directory containing images and videos. In my application, I have a collection that displays images in each cell.

I accomplished this with an image upload function that returns a UIImage

// Get the UI Image from the path passed in let image = UIImage(contentsOfFile: path) if image == nil { print("No Image at this path"); } else { return image } 

However, I cannot find something equivalent for the video. Ideally, I want it to show as a video player, as in a photo album, where you still see the video with a small play button on it, which is when you press the video playback.

If you cannot get a still video on the specified path, I should be returned as a UIImage , which I can display will be fine.

I'm new to iOS, so it's just interesting if there is some equivalent type like UIImage for video, which means that I can just load and display it as a collection.

+5
source share
3 answers

You need to take a snapshot of the video and display it along with the play button. Here is my func in Swift 2 , which can get you a video snapshot for the video file along the filePathLocal path:

 func videoSnapshot(filePathLocal: NSString) -> UIImage? { let vidURL = NSURL(fileURLWithPath:filePathLocal as String) let asset = AVURLAsset(URL: vidURL) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true let timestamp = CMTime(seconds: 1, preferredTimescale: 60) do { let imageRef = try generator.copyCGImageAtTime(timestamp, actualTime: nil) return UIImage(CGImage: imageRef) } catch let error as NSError { print("Image generation failed with error \(error)") return nil } } 
+18
source

version of Swift 3

 func videoPreviewUiimage(fileName:String) -> UIImage? { let filePath = NSString(string: "~/").expandingTildeInPath.appending("/Documents/").appending(fileName) let vidURL = NSURL(fileURLWithPath:filePath) let asset = AVURLAsset(url: vidURL as URL) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true let timestamp = CMTime(seconds: 2, preferredTimescale: 60) do { let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil) return UIImage(cgImage: imageRef) } catch let error as NSError { print("Image generation failed with error \(error)") return nil } } 

Based on Nishant's answer above.

+8
source

For quick 3.0

 func generateThumbnailForVideoAtURL(filePathLocal: NSString) -> UIImage? { let vidURL = NSURL(fileURLWithPath:filePathLocal as String) let asset = AVURLAsset(url: vidURL as URL) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true let timestamp = CMTime(seconds: 1, preferredTimescale: 60) do { let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil) return UIImage(cgImage: imageRef) } catch let error as NSError { print("Image generation failed with error \(error)") return nil } } 
+3
source

All Articles