gpt4 book ai didi

ios - 从视频中提取缩略图时出现黑色空白图像

转载 作者:行者123 更新时间:2023-11-29 05:54:23 29 4
gpt4 key购买 nike

我正在尝试使用 AVFoundation 从 URL 的视频中获取缩略图,但我收到了附件中的黑色空白图像。

视频网址为https://www.riptide.tv/app/assets/2/3/small_3001190658061_2.mp4

下面是我的代码:

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
downloadedThumbnails.updateValue(thumbnail, forKey: imgName)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}

black img extracted

最佳答案

如果您将代码更改为

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(5), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}

5 秒后。您可以看到生成的缩略图。

Thumbnail

这是因为 AVAssetImageGenerator 在获取帧的时间方面非常灵活

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
assetImgGenerate.requestedTimeToleranceAfter = .zero
assetImgGenerate.requestedTimeToleranceBefore = .zero
let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
do {
let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
return UIImage(named: imgName)
}
}

设置

assetImgGenerate.requestedTimeToleranceAfter = .zero
assetImgGenerate.requestedTimeToleranceBefore = .zero

确保您获得帧精确的缩略图。

有关更多信息,请参阅 https://developer.apple.com/documentation/avfoundation/avassetimagegenerator/1390571-requestedtimetolerancebefore

关于ios - 从视频中提取缩略图时出现黑色空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300035/

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