如angular1 question here doesn't work中所述,我使用以下代码从视频网址生成缩略图:
//MARK: - - Generate Thumbnail
func getThumbnailFrom(path: URL) -> UIImage? {
do {
let asset = AVURLAsset(url: path, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let uiImage = UIImage.init(cgImage: cgImage)
return uiImage
} catch let error as NSError {
print("Error generating thumbnail: \(error.localizedDescription)")
return nil
}
}
但它引发了一个错误:
生成缩略图时出错:操作无法完成
答案 0 :(得分:0)
使用以下代码从视频网址生成拇指图像。
DispatchQueue.global().async {
let asset = AVAsset(url: "**your url of video**")
let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMake(1, 2)
let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)
if img != nil {
let frameImg = UIImage(cgImage: img!)
DispatchQueue.main.async(execute: {
// assign your image to UIImageView
})
}
}
答案 1 :(得分:-1)
嘿我也对视频缩略图使用了相同的逻辑。
do {
let videoUrl = "Url"
let asset = AVURLAsset(url: videoUrl, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
// Rotate image before proceeding
let uiImage = UIImage(cgImage: cgImage, scale: CGFloat(1.0), orientation: .right)
image = uiImage
} catch let error as NSError {
print("Error occurred: \(error)")
}
它对我有用。获得CGImage
图像方向不正确后,使方向正确。看看它是否适合你。