I\'m trying to get thumbnail from video and show it in my tableview. Here is my code:
- (UIImage *)imageFromVideoURL:(NSURL *)contentURL {
AVAsset *asse
SWIFT 5.2 VERSION:
You can find my original post here, where I took inspiration from rozochkin's answer.
func getCurrentFrame() -> UIImage? {
guard let player = self.player, let avPlayerAsset = player.currentItem?.asset else {return nil}
let assetImageGenerator = AVAssetImageGenerator(asset: avPlayerAsset)
assetImageGenerator.requestedTimeToleranceAfter = .zero
assetImageGenerator.requestedTimeToleranceBefore = .zero
assetImageGenerator.appliesPreferredTrackTransform = true
let imageRef = try! assetImageGenerator.copyCGImage(at: player.currentTime(), actualTime: nil)
let image = UIImage(cgImage: imageRef)
return image
}
IMPORTANT NOTES:
requestedTimeToleranceAfter and requestedTimeToleranceBefore should be set to .zero, because, according to source code, "The actual time of the generated images [...] may differ from the requested time for efficiency".
appliesPreferredTrackTransform must be set to TRUE (default is FALSE), otherwise you get a bad-rotated frame. With this property set to TRUE you get what you really see in the player.
func getThumbnailFrom(path: URL) -> UIImage? {
do {
let asset = AVURLAsset(url: path , options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let timestamp = asset.duration
print("Timestemp: \(timestamp)")
let cgImage = try imgGenerator.copyCGImage(at: timestamp, actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
return thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
return nil
}
}
This Code is working.