gpt4 book ai didi

iOS - 如何在不播放的情况下从视频中获取缩略图?

转载 作者:技术小花猫 更新时间:2023-10-29 11:00:41 24 4
gpt4 key购买 nike

我正在尝试从视频中获取缩略图并将其显示在我的表格 View 中。这是我的代码:

- (UIImage *)imageFromVideoURL:(NSURL *)contentURL {
AVAsset *asset = [AVAsset assetWithURL:contentURL];

// Get thumbnail at the very start of the video
CMTime thumbnailTime = [asset duration];
thumbnailTime.value = 25;

// Get image from the video at the given time
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];

CGImageRef imageRef = [imageGenerator copyCGImageAtTime:thumbnailTime actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

return thumbnail;
}

但是图像总是返回黑色。怎么了?

最佳答案

使用 Swift 5,作为 AVAsset 的扩展函数:

import AVKit

extension AVAsset {

func generateThumbnail(completion: @escaping (UIImage?) -> Void) {
DispatchQueue.global().async {
let imageGenerator = AVAssetImageGenerator(asset: self)
let time = CMTime(seconds: 0.0, preferredTimescale: 600)
let times = [NSValue(time: time)]
imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { _, image, _, _, _ in
if let image = image {
completion(UIImage(cgImage: image))
} else {
completion(nil)
}
})
}
}
}

用法:

            AVAsset(url: url).generateThumbnail { [weak self] (image) in
DispatchQueue.main.async {
guard let image = image else { return }
self?.imageView.image = image
}
}

关于iOS - 如何在不播放的情况下从视频中获取缩略图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32691304/

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