gpt4 book ai didi

ios - 输入什么来异步生成 CGImages

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:32 25 4
gpt4 key购买 nike

在我的应用中,我想生成一个视频的多个缩略图,最好是质量好的缩略图。我的旧方法是执行一个循环 15 次,并在不同的时间复制一个 CGImage。如下图

func generateThumbnails(_ fileURL:URL) {
let asset = AVAsset(url: fileURL)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.apertureMode = AVAssetImageGeneratorApertureMode.cleanAperture
imageGenerator.appliesPreferredTrackTransform = true
let duration = asset.duration
let seconds = CMTimeGetSeconds(duration)
let addition = seconds / 15
var number = 1.0
do {
while number < seconds {
let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(Int64(number),1), actualTime: nil)
let image = UIImage(cgImage: thumbnailCGImage)
thumbnails.append(image)
number += addition
}
} catch let err {
return
}
}

然而,在做了更多研究之后,我发现使用异步生成缩略图更符合逻辑

let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue], completionHandler: AVAssetImageGeneratorCompletionHandler)

但是,我真的不知道应该向 [NSValue] 和完成处理程序输入什么。

我只需要解释如何以这种方式生成缩略图,看看这样做是否更好。

最佳答案

https://developer.apple.com/documentation/avfoundation/avassetimagegenerator/1388100-generatecgimagesasynchronously

requestedTimes An array of NSValue objects, each containing a CMTime, specifying the asset times at which an image is requested.

用法:

let duration = asset.duration
let seconds = CMTimeGetSeconds(duration)
let addition = seconds / 15
var number = 1.0

var times = [NSValue]()
times.append(NSValue(time: CMTimeMake(Int64(number), 1)))
while number < seconds {
number += addition
times.append(NSValue(time: CMTimeMake(Int64(number), 1)))
}

struct Formatter {
static let formatter: DateFormatter = {
let result = DateFormatter()
result.dateStyle = .short
return result
}()
}

imageGenerator.generateCGImagesAsynchronously(forTimes: times) { (requestedTime, cgImage, actualImageTime, status, error) in

let seconds = CMTimeGetSeconds(requestedTime)
let date = Date(timeIntervalSinceNow: seconds)
let time = Formatter.formatter.string(from: date)

switch status {
case .succeeded: do {
if let image = cgImage {
print("Generated image for approximate time: \(time)")

let img = UIImage(cgImage: image)
//do something with `img`
}
else {
print("Failed to generate a valid image for time: \(time)")
}
}

case .failed: do {
if let error = error {
print("Failed to generate image with Error: \(error) for time: \(time)")
}
else {
print("Failed to generate image for time: \(time)")
}
}

case .cancelled: do {
print("Image generation cancelled for time: \(time)")
}
}
}

关于ios - 输入什么来异步生成 CGImages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48046633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com