swift – generateCGImagesAsynchronouslyForTimes有时不会生成完整的缩略图

前端之家收集整理的这篇文章主要介绍了swift – generateCGImagesAsynchronouslyForTimes有时不会生成完整的缩略图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一个使用AVAsset ImageGenerator.generateCGImagesAsynchronouslyForTimes的OS X应用程序,它通常工作正常.然而,一段时间后,我回来的缩略图只包含前几行像素,其余的是绿色,有时图像将是不同的绿色.很难跟踪,因为它不会一直发生,但是当大约一半的缩略图受到影响时.这是我期望看到的形象:

但经常发生这种情况:

以下是我用来生成缩略图代码

let assetGenerator = AVAssetImageGenerator(asset: AVURLAsset(URL: url))
assetGenerator.appliesPreferredTrackTransform = true
let time = CMTime(seconds: 0,preferredTimescale: 30)

let handler: AVAssetImageGeneratorCompletionHandler = { _,image,_,res,error in
    defer { dispatch_group_leave(self.waitForThumbnail!) }

    guard let image = image where res == .Succeeded else {
        if let error = error { print(error) }
        return
    }

    let s = CGSize(width: CGImageGetWidth(image),height: CGImageGetHeight(image))
    self.thumbnail = NSImage(CGImage: image,size: s)

}

waitForThumbnail = dispatch_group_create()
dispatch_group_enter(waitForThumbnail!)

assetGenerator.maximumSize = maxThumbnailSize
assetGenerator.generateCGImagesAsynchronouslyForTimes([NSValue(CMTime: time)],completionHandler: handler)

这就是我如何检索缩略图

dispatch_group_wait(file.waitForThumbnail!,DISPATCH_TIME_FOREVER)
dispatch_async(dispatch_get_main_queue()) {
    self.imageView.image = file.thumbnail
}

非常感谢任何帮助,谢谢!

而不是使用generateCGImagesAsynchronouslyForTimes方法,您可以使用copyCGImageAtTime方法从资产中获取图像,并保存该图像.这是代码.
let assetGenerator = AVAssetImageGenerator(asset: AVURLAsset(URL: url))
assetGenerator.appliesPreferredTrackTransform = true
assetGenerator.maximumSize = maxThumbnailSize
let time = CMTime(seconds: 0,preferredTimescale: 30)
do {
    let cgImage = try assetGenerator.copyCGImageAtTime(time,actualTime: nil)
    let s = CGSize(width: CGImageGetWidth(cgImage),height: CGImageGetHeight(cgImage))
    self.thumbnail = NSImage(CGImage: cgImage,size: s)    
} catch let error {
    print(error)
}
原文链接:https://www.f2er.com/swift/318940.html

猜你在找的Swift相关文章