0

As mentioned in this answer, I am using below code to generate thumbnail from Video URL:

//MARK: - - Generate Thumbnail
func getThumbnailFrom(path: URL) -> UIImage? {

    do {

        let asset = AVURLAsset(url: path, options: nil)

        let imgGenerator = AVAssetImageGenerator(asset: asset)
        imgGenerator.appliesPreferredTrackTransform = true

        let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
        let uiImage = UIImage.init(cgImage: cgImage)

        return uiImage


    } catch let error as NSError {

        print("Error generating thumbnail: \(error.localizedDescription)")
        return nil
    }
}

but it is throwing an error:

Error generating thumbnail: The operation could not be completed

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Sandip Gill
  • 1,060
  • 1
  • 11
  • 22

2 Answers2

0

Use below code for generating thumb image from video url.

DispatchQueue.global().async {
    let asset = AVAsset(url: "**your url of video**")
    let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
     assetImgGenerate.appliesPreferredTrackTransform = true
    let time = CMTimeMake(1, 2)
    let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)
    if img != nil {
    let frameImg  = UIImage(cgImage: img!)
                    DispatchQueue.main.async(execute: {
    // assign your image to UIImageView
                    })
            }
    }
Harshit
  • 107
  • 1
  • 6
-1

Hey I have also used same logic for thumbnail of video.

        do {
            let videoUrl = "Url"

            let asset = AVURLAsset(url: videoUrl, options: nil)
            let imgGenerator = AVAssetImageGenerator(asset: asset)

            let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)

            // Rotate image before proceeding
            let uiImage = UIImage(cgImage: cgImage, scale: CGFloat(1.0), orientation: .right)

            image = uiImage

        } catch let error as NSError {

            print("Error occurred: \(error)")
        }

It works for me. After getting CGImage image orientation was not proper so made orientation proper. See if it works for you.

Swapnil Dhotre
  • 375
  • 4
  • 21
  • file:///var/mobile/Containers/Data/Application/007D2DC0-99F5-4C13-90D6-B58E8BB61E14/Documents/video.mp4 this is my file url – Sandip Gill Jan 04 '18 at 13:11