Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get thumbnail image of video picked from UIPickerViewController in Swift?

Tags:

ios

swift

This is how I access the video:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

    if let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL {
        let video = NSData(contentsOfURL: videoURL)
    }
}

That video I would like to show the user in my controller (I do not mean UIDocumentInteractionController to preview this). I need a thumbnail of that video, and then assign this to UIImageView. Is it possible?

like image 211
Bartłomiej Semańczyk Avatar asked Nov 28 '22 23:11

Bartłomiej Semańczyk


2 Answers

The simplest answer:

import AVFoundation

private func thumbnailForVideoAtURL(url: NSURL) -> UIImage? {

    let asset = AVAsset(URL: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImageAtTime(time, actualTime: nil)
        return UIImage(CGImage: imageRef)
    } catch {
        print("error")
        return nil
    }
}
like image 195
Bartłomiej Semańczyk Avatar answered Dec 01 '22 14:12

Bartłomiej Semańczyk


Here's SWIFT 3.0 using extension

import Foundation
import UIKit
import MediaPlayer

import SystemConfiguration

extension AVAsset{
    var videoThumbnail:UIImage?{

        let assetImageGenerator = AVAssetImageGenerator(asset: self)
        assetImageGenerator.appliesPreferredTrackTransform = true

        var time = self.duration
        time.value = min(time.value, 2)

        do {
            let imageRef = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
            let thumbNail = UIImage.init(cgImage: imageRef)


            print("Video Thumbnail genertated successfuly".DubugSuccess())

            return thumbNail

        } catch {

            print("error getting thumbnail video".DubugError(),error.localizedDescription)
            return nil


        }

    }
}

Then simply from anywhere you have access to AVAsset/URL:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

    if let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL {
        let video = NSData(contentsOfURL: videoURL)

        //Create AVAsset from url
        let ass = AVAsset(url:videoURL)

        if let videoThumbnail = ass.videoThumbnail{
          print("Success")
        }
    }
}
like image 25
Jad Avatar answered Dec 01 '22 12:12

Jad