Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get thumbail / preview image from a server video URL in Swift 3.0

Tags:

ios

swift

swift3

I want a thumbnail image from a video underlying on the server. The video file is not on local. It's on my server. The video file has extension .m3u8.

like image 472
Charmi Avatar asked Feb 09 '17 06:02

Charmi


2 Answers

You can do it.

First step: You need to import AVFoundation:

    import AVFoundation

Then add the code below to your controller:

func getThumbnailImage(forUrl url: URL) -> UIImage? {
    let asset: AVAsset = AVAsset(url: url)
    let imageGenerator = AVAssetImageGenerator(asset: asset)

    do {
        let thumbnailImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1, timescale: 60), actualTime: nil)
        return UIImage(cgImage: thumbnailImage)
    } catch let error {
        print(error)
    }

    return nil
}

Usage:

    let imageView = UIImageView()
    let url = URL(string: "your_video_url")

    if let thumbnailImage = getThumbnailImage(forUrl: url) {
        imageView.image = thumbnailImage
    }

Change url to your video link.

like image 90
javimuu Avatar answered Oct 02 '22 13:10

javimuu


Step 1

import AVFoundation

Step 2

Add the following function in your ViewController:

func getThumbnailImageFromVideoUrl(url: URL, completion: @escaping ((_ image: UIImage?)->Void)) {
    DispatchQueue.global().async { //1
        let asset = AVAsset(url: url) //2
        let avAssetImageGenerator = AVAssetImageGenerator(asset: asset) //3
        avAssetImageGenerator.appliesPreferredTrackTransform = true //4
        let thumnailTime = CMTimeMake(value: 2, timescale: 1) //5
        do {
            let cgThumbImage = try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil) //6
            let thumbNailImage = UIImage(cgImage: cgThumbImage) //7
            DispatchQueue.main.async { //8
                completion(thumbNailImage) //9
            }
        } catch {
            print(error.localizedDescription) //10
            DispatchQueue.main.async {
                completion(nil) //11
            }
        }
    }
}

Step 3

self.getThumbnailImageFromVideoUrl(url: videoUrl) { (thumbNailImage) in
    self.yourImageView.image = thumbNailImage
}

If you need a complete explanation, refer to Get a thumbnail from a video URL in the background in Swift.

like image 23
Sai kumar Reddy Avatar answered Oct 02 '22 11:10

Sai kumar Reddy