gpt4 book ai didi

swift - 无法从 ios 13 中的 url 视频生成缩略图

转载 作者:行者123 更新时间:2023-11-28 07:20:40 24 4
gpt4 key购买 nike

我正在使用下面的代码从视频 URL 生成一个帧。这段代码在之前的一段时间内运行良好。现在它不起作用。它抛出无法解码的错误并且文件可能已损坏。有人可以帮忙吗?

func previewImageFromVideo(url: NSURL) -> UIImage? {
let url = url as URL
let request = URLRequest(url: url)
let cache = URLCache.shared

if
let cachedResponse = cache.cachedResponse(for: request),
let image = UIImage(data: cachedResponse.data)
{
return image
}

let asset = AVAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.maximumSize = CGSize(width: 250, height: 120)

var time = asset.duration
time.value = min(time.value, 2)

var image: UIImage?

do {
let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
image = UIImage(cgImage: cgImage)
} catch { }

if
let image = image,
let data = UIImagePNGRepresentation(image),
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)
{
let cachedResponse = CachedURLResponse(response: response, data: data)

cache.storeCachedResponse(cachedResponse, for: request)
}

return image
}

此代码在从 URL 视频捕获帧时抛出错误。它说文件可能已损坏。

最佳答案

我在 Playground 上试过你的代码,它工作得很好。如错误消息所述,文件可能已损坏。

import UIKit
import AVKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
container.addSubview(imageView)

PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true

func previewImageFromVideo(url: NSURL) -> UIImage? {
let url = url as URL
let request = URLRequest(url: url)
let cache = URLCache.shared

if
let cachedResponse = cache.cachedResponse(for: request),
let image = UIImage(data: cachedResponse.data)
{
return image
}

let asset = AVAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.maximumSize = CGSize(width: 250, height: 120)

var time = asset.duration
time.value = min(time.value, 2)

var image: UIImage?

do {
let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
image = UIImage(cgImage: cgImage)
} catch { }

if
let image = image,
let data = image.pngData(),
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)
{
let cachedResponse = CachedURLResponse(response: response, data: data)

cache.storeCachedResponse(cachedResponse, for: request)
}

return image
}

imageView.image = previewImageFromVideo(url: NSURL(string: "https://www.w3schools.com/html/mov_bbb.mp4")!)

关于swift - 无法从 ios 13 中的 url 视频生成缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260806/

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