ios - 快速从视频中提取帧

标签 ios objective-c swift

我正在尝试从 Swift 中的视频中提取帧作为 UIImage。我找到了几个 Objective C 解决方案,但我在 Swift 中找不到任何东西。假设以下内容是正确的,有人可以帮助我将以下内容转换为 Swift 或让我了解如何执行此操作吗?

来源: Grabbing the first frame of a video from UIImagePickerController?

- (UIImage *)imageFromVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetIG =
    [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetIG.appliesPreferredTrackTransform = YES;
    assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *igError = nil;
    thumbnailImageRef =
    [assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)
                    actualTime:NULL
                         error:&igError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", igError );
    
    UIImage *image = thumbnailImageRef
    ? [[UIImage alloc] initWithCGImage:thumbnailImageRef]
    : nil;
    
    return image;
}

最佳答案

它确实有效。

func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
    let asset = AVURLAsset(url: url)

    let assetIG = AVAssetImageGenerator(asset: asset)
    assetIG.appliesPreferredTrackTransform = true
    assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels

    let cmTime = CMTime(seconds: time, preferredTimescale: 60)
    let thumbnailImageRef: CGImage
    do {
        thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
    } catch let error {
        print("Error: \(error)")
        return nil
    }

    return UIImage(cgImage: thumbnailImageRef)
}

但是记住这个函数是同步的,最好不要在主队列上调用它。

你可以这样做:

DispatchQueue.global(qos: .background).async {
    let image = self.imageFromVideo(url: url, at: 0)

    DispatchQueue.main.async {
        self.imageView.image = image
    }
}

或者使用generateCGImagesAsynchronously而不是 copyCGImage

关于ios - 快速从视频中提取帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520453/

相关文章:

ios - 作为 willActivate 的一部分更新界面时的奇怪行为

ios - iOS 中的滚动菜单

ios - 从 Swift 转换为 Objective C,为什么这段代码只能工作一次?

ios - 当设备以横向启动时,UIDevice 方向返回纵向

ios - 内联日期选择器的实现

ios - 发布旋转 UIImage

objective-c - 接收udp广播包ios

objective-c - 使用 componentsSeparatedByString 拆分 NSString

xcode - 将 Swift 应用程序分解为框架

ios - Game Center 和 Apple 登录有什么区别?