我想从视频中提取帧作为 UIImage 。这就是我使用AVAssetImageGenerator
.
首先我保存了times
var frameCount = 0;
var maximumFrame = 300;
let duration = asset.duration
let vid_length : CMTime = duration
let timeScale = vid_length.timescale
let seconds : Double = CMTimeGetSeconds(vid_length)
var times = [CMTime]()
var timeForGetImage : Double = 0
let step : Double = 0.033
while(frameCount < maximumFrame && timeForGetImage <= seconds) {
let time : CMTime = CMTimeMakeWithSeconds(timeForGetImage, preferredTimescale: timeScale)
times.append(time)
timeForGetImage+=step
frameCount += 1
}
为了获取帧作为图像,我使用了这种方法
let imageGenerator : AVAssetImageGenerator = AVAssetImageGenerator.init(asset: asset)
imageGenerator.requestedTimeToleranceAfter = CMTime.zero
imageGenerator.requestedTimeToleranceBefore = CMTime.zero
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.maximumSize = CGSize(width: height, height: height)
imageGenerator.generateCGImagesAsynchronously(forTimes: times as [NSValue]) { (requestedTime, cgImage, actualTime, result, error) in
if result == .succeeded {
let thumb : UIImage = UIImage.init(cgImage: cgImage!)
/// doing some operation
} else {
print("nil") /// I've found some images are nil
}
}
在这里,我得到了一些 nil cgImages。我不知道为什么他们是零。但我需要使用时间段将所有帧作为 cgImages 获取。
怎么解决?
我知道还有另一种使用方法的imageGenerator.copyCGImage
方法。但是将所有帧生成为 UIImage 需要太多时间```