我正在尝试从视频中获取缩略图并在我的tableview中显示它.这是我的代码:
- (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;
}
但是图像总是回归黑色.怎么了?
解决方法
用这个 :
斯威夫特3 –
斯威夫特3 –
func createThumbnailOfVideoFromFileURL(videoURL: String) -> UIImage? {
let asset = AVAsset(url: URL(string: videoURL)!)
let assetImgGenerate = AVAssetimageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(Float64(1),100)
do {
let img = try assetImgGenerate.copyCGImage(at: time,actualTime: nil)
let thumbnail = UIImage(cgImage: img)
return thumbnail
} catch {
return UIImage(named: "ico_placeholder")
}
}
重要的提示 :
你需要在if else中使用它,因为它是资源广泛的.您必须将图像存储在数组或模型中,并检查是否一旦创建了缩略图,它就会引用缓存/数组,以便cellForRowAtIndexPath不会导致滚动UITableView的延迟