iOS - 如何在没有游戏的情况下从视频获取缩略图?

时间:2015-09-21 09:08:26

标签: ios image video-thumbnails

我正在尝试从视频中获取缩略图并在我的tableview中显示它。这是我的代码:

Total Payout: ->Capture<-

但是图像总是会变黑。怎么了?

8 个答案:

答案 0 :(得分:6)

使用此: 斯威夫特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

答案 1 :(得分:2)

NSURL *videoURL = [NSURL fileURLWithPath:filepath];// filepath is your video file path 



AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *error = NULL;
CMTime time = CMTimeMake(1, 1);
CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&error];
NSLog(@"error==%@, Refimage==%@", error, refImg);

UIImage *FrameImage= [[UIImage alloc] initWithCGImage:refImg];
return FrameImage;

答案 2 :(得分:2)

只需使用此代码。传递您的视频网址并获取图片。

+(UIImage *)getPlaceholderImageFromVideo:(NSString *)videoURL {
    NSURL *url = [NSURL URLWithString:videoURL];
    AVAsset *asset = [AVAsset assetWithURL:url];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    CMTime time = [asset duration];
    time.value = 0;
    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return thumbnail;
}

希望,这就是你要找的东西。任何关注都会回复给我。 :)

答案 3 :(得分:1)

请查看&#34;从视频&#34;

生成缩略图的链接

https://littlebitesofcocoa.com/115-generating-thumbnails-from-videos

应用需要在视频中显示一个或多个缩略图(小型静态图像预览),这很常见。但是,根据视频的来源,我们可能无法轻松访问预制缩略图。让我们看一下如何使用AVAssetImageGenerator来获取我们自己的东西。 我们从视频的简单NSURL开始,这可以是本地的或远程的。我们将使用它创建一个AVAsset,并创建一个新的AVAssetImageGenerator对象。我们将生成器配置为应用首选变换,以使我们的缩略图方向正确。

import AVFoundation

if let asset = AVAsset(URL: videoURL) {
   let durationSeconds = CMTimeGetSeconds(asset.duration)
   let generator = AVAssetImageGenerator(asset: asset)

   generator.appliesPreferredTrackTransform = true

   let time = CMTimeMakeWithSeconds(durationSeconds/3.0, 600)
   var thumbnailImage: CGImageRef 
   generator.generateCGImagesAsynchronouslyForTimes([NSValue(CMTime: time)]) { 
       (requestedTime: CMTime, thumbnail: CGImage?, actualTime: CMTime, result: AVAssetImageGeneratorResult, error: NSError?) in
      self.videoThumbnailImageView.image = UIImage(CGImage: thumbnail)
    }
}

答案 4 :(得分:1)

为@Disha的答案提供4个代码:

let imageGenerator = AVAssetImageGenerator(asset: avAsset)
                let time = CMTime(seconds: seconds, preferredTimescale: 600)
                let times = [NSValue(time: time)]
                imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: {
                    requestedTime, image, actualTime, result, error in
                    guard let cgImage = image else
                    {
                        print("No image!")
                        return
                    }
                    let uiImage = UIImage(cgImage: cgImage)
                    UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil);
                })

答案 5 :(得分:1)

使用Swift 5作为AVAsset的扩展功能:

import AVKit

extension AVAsset {

    func generateThumbnail(completion: @escaping (UIImage?) -> Void) {
        DispatchQueue.global().async {
            let imageGenerator = AVAssetImageGenerator(asset: self)
            let time = CMTime(seconds: 0.0, preferredTimescale: 600)
            let times = [NSValue(time: time)]
            imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { _, image, _, _, _ in
                if let image = image {
                    completion(UIImage(cgImage: image))
                } else {
                    completion(nil)
                }
            })
        }
    }
}

用法:

            AVAsset(url: url).generateThumbnail { [weak self] (image) in
                DispatchQueue.main.async {
                    guard let image = image else { return }
                    self?.imageView.image = image
                }
            }

答案 6 :(得分:0)

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
          }
        }

此代码有效。

答案 7 :(得分:0)

SWIFT 5.2版本:

您可以找到我的原始帖子here,是我从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
}

重要说明:

requestedTimeToleranceAfter requestedTimeToleranceBefore 应该设置为.zero,因为根据源代码,“生成图像的实际时间可能与[...]要求的效率时间”。

appliesPreferredTrackTransform 必须设置为 TRUE (默认为FALSE),否则会出现帧旋转不良。将此属性设置为TRUE,您将获得在播放器中真正看到的内容。