Display a preview image from a video swift

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

func videoSnapshot(filePathLocal: String) -> UIImage? {

    let vidURL = URL(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.copyCGImage(at: timestamp, actualTime: nil)
        return UIImage(cgImage: imageRef)
    }
    catch let error as NSError
    {
        print("Image generation failed with error \(error)")
        return nil
    }
}

Using a URL for your path is better than using String:

func videoPreviewImage(url: URL) -> UIImage? {
    let asset = AVURLAsset(url: url)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true
    if let cgImage = try? generator.copyCGImage(at: CMTime(seconds: 2, preferredTimescale: 60), actualTime: nil) {
        return UIImage(cgImage: cgImage)
    }
    else {
        return nil
    }
}

Swift 3 version

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 answer above.

Tags:

Ios

Swift