generateCGImagesAsynchronouslyForTimes有时不会生成整个缩略图

时间:2016-08-03 14:51:58

标签: swift avfoundation thumbnails avassetimagegenerator

我正在使用AVAssetImageGenerator.generateCGImagesAsynchronouslyForTimes的OS X应用程序,它通常可以正常工作。然而,偶尔我回来的缩略图只包含前几行像素,其余的是绿色,有时图像将是不同的绿色阴影。它很难追踪,因为它不会一直发生,但是当它确实有大约一半的缩略图受到影响时。这是我期望看到的图像:

enter image description here

但有时会发生这种情况:

enter image description here

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

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
}

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

1 个答案:

答案 0 :(得分:2)

我认为您的问题实际上是CGImageAVAssetImageGenerator.generateCGImagesAsynchronouslyForTimes返回的 /*! @method generateCGImagesAsynchronouslyForTimes:completionHandler: @abstract Returns a series of CGImageRefs for an asset at or near the specified times. @param requestedTimes An NSArray of NSValues, each containing a CMTime, specifying the asset times at which an image is requested. @param handler A block that will be called when an image request is complete. @discussion Employs an efficient "batch mode" for getting images in time order. The client will receive exactly one handler callback for each requested time in requestedTimes. Changes to generator properties (snap behavior, maximum size, etc...) will not affect outstanding asynchronous image generation requests. The generated image is not retained. Clients should retain the image if they wish it to persist after the completion handler returns. */ - (void)generateCGImagesAsynchronouslyForTimes:(NSArray<NSValue *> *)requestedTimes completionHandler:(AVAssetImageGeneratorCompletionHandler)handler; 未被保留。有趣的是,official documentation没有提到这一点,但是阅读头文件明确地说明了这一点。

CGImage

我相信保留这些ForeignKey会解决问题。