如何使用Swift中的copyCGImageAtTime从视频创建缩略图?

时间:2015-07-02 16:33:35

标签: swift thumbnails

我正在尝试使用copyCGImageAtTime从视频创建缩略图,但我一直收到以下错误:

  

致命错误:在打开Optional时意外发现nil   值。

我在调用copyCGImageAtTime后使用了中断,发现imgnil。我做错了什么?

这是我的代码:

 func generateThumbnail() -> UIImage
 {
        var fileArray = NSBundle.mainBundle().pathsForResourcesOfType    (".mp4", inDirectory: "")
        var moviePath : String = fileArray[1] as! String
        let url = NSURL(string: moviePath)
        var asset : AVAsset = AVAsset.assetWithURL(url) as! AVAsset
        var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true
        var durationSeconds: Float64 = CMTimeGetSeconds(asset.duration)
        var time: CMTime = CMTimeMakeWithSeconds(durationSeconds/2.0, 600)
        var actualTime: UnsafeMutablePointer<CMTime> = nil
        var error: NSErrorPointer = nil
        var img: CGImage! = assetImgGenerate.copyCGImageAtTime(time, actualTime: actualTime, error: error)
        var frameImg : UIImage = UIImage(CGImage: img)!
        return frameImg
}

1 个答案:

答案 0 :(得分:2)

这对我有用。但是,我从这个方法中获得了信息。也许你可以根据你的代码进行调整。

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let tempImage = info[UIImagePickerControllerMediaURL] as! NSURL!
let pathString = tempImage.relativePath

var url:NSURL = NSURL(fileURLWithPath: pathString!)!
var asset:AVAsset = AVAsset.assetWithURL(url) as! AVAsset
var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
var time: CMTime = asset.duration
    time.value = 0

var imageRef: CGImage! = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: nil)

var frameImg : UIImage = UIImage(CGImage: imageRef)!

return framImg
}