在swift中从本地视频创建缩略图

时间:2015-08-03 03:49:46

标签: ios swift iphone video-capture

如何使用本地视频文件在swift中创建缩略图?

例如,如果视频文件路径位于此处:

file:///Users/Dev/Library/Developer/CoreSimulator/Devices/F33222DF-D8F0-448B-A127-C5B03C64D0DC/data/Containers/Data/Application/4BC62DBF-0108-453C-9324-5BC0E356FE24/tmp/trim.059D11E6-F0EF-43DB-9E97-CA4F1F95D6B6.MOV

谢谢。

7 个答案:

答案 0 :(得分:52)

通过以下编辑进行翻译:

First frame of a video using AVFoundation

    var err: NSError? = nil
    let asset = AVURLAsset(URL: NSURL(fileURLWithPath: "/that/long/path"), options: nil)
    let imgGenerator = AVAssetImageGenerator(asset: asset)
    let cgImage = imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil, error: &err)
    // !! check the error before proceeding
    let uiImage = UIImage(CGImage: cgImage)
    let imageView = UIImageView(image: uiImage)
    // lay out this image view, or if it already exists, set its image property to uiImage

答案 1 :(得分:52)

BaseZen的答案翻译 Swift 3 / Swift 4

您需要将要制作缩略图的视频的位置设置为网址资源路径,例如:

别忘了import AVFoundation

func generateThumbnail(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(value: 0, timescale: 1), actualTime: nil)
        let thumbnail = UIImage(cgImage: cgImage)
        return thumbnail
    } catch let error {
        print("*** Error generating thumbnail: \(error.localizedDescription)")
        return nil
    }
}

对于遇到此问题的每个人,我在Github

上托管的示例中创建了以下内容

答案 2 :(得分:19)

这是David的答案的清理版本,并针对iOS 11 / Swift 4.x进行了测试。

请注意根据您使用的Swift版本处理初始时间的不同调用。

func generateThumbnail(url: URL) -> UIImage? {
    do {
        let asset = AVURLAsset(url: url)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        // Select the right one based on which version you are using
        // Swift 4.2
        let cgImage = try imageGenerator.copyCGImage(at: .zero,
                                                     actualTime: nil)
        // Swift 4.0
        let cgImage = try imageGenerator.copyCGImage(at: kCMTimeZero,
                                                     actualTime: nil)


        return UIImage(cgImage: cgImage)
    } catch {
        print(error.localizedDescription)

        return nil
    }
}
  1. 根据提供的AVURLAsset
  2. 创建URL
  3. 使用新创建的AVAssetImageGenerator创建AVURLAsset,负责制作缩略图
  4. appliesPreferredTrackTransform通知生成器将矩阵应用于缩略图生成。默认值为false。
  5. 尝试在视频曲目的第一帧创建CGImage
  6. 使用新创建的CGImage&创建UIImage。退货
  7. 如果图像生成步骤失败,则会捕获错误并将其与nil UIImage一起呈现给控制台

答案 3 :(得分:12)

BaseZen的答案翻译成Swift 2:

import UIKit
import AVFoundation

do {
    let asset = AVURLAsset(URL: NSURL(fileURLWithPath: "/that/long/path"), options: nil)
    let imgGenerator = AVAssetImageGenerator(asset: asset)
    imgGenerator.appliesPreferredTrackTransform = true
    let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil)
    let uiImage = UIImage(CGImage: cgImage)
    let imageView = UIImageView(image: uiImage)
    // lay out this image view, or if it already exists, set its image property to uiImage
} catch let error as NSError {
    print("Error generating thumbnail: \(error)")
}

答案 4 :(得分:4)

编写较少且简单的代码以便理解会更好。 这就是我在Swift中转换解决方案(3.1 ... 4.2)

import AVFoundation

func videoPreviewUIImage(moviePath: URL) -> UIImage? {
    let asset = AVURLAsset(url: moviePath)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true
    let timestamp = CMTime(seconds: 2, preferredTimescale: 60)
    if let imageRef = try? generator.copyCGImage(at: timestamp, actualTime: nil) {
        return UIImage(cgImage: imageRef)
    } else {
        return nil
    }
}

希望它会对某人有所帮助。

答案 5 :(得分:0)

Swift 5.3

作为其他答案的替代方法,我稍加修改后决定进行URL扩展。

import AVFoundation

extension URL {
    func generateThumbnail() -> UIImage? {
        do {
            let asset = AVURLAsset(url: self)
            let imageGenerator = AVAssetImageGenerator(asset: asset)
            imageGenerator.appliesPreferredTrackTransform = true
            
            // Swift 5.3
            let cgImage = try imageGenerator.copyCGImage(at: .zero,
                                                         actualTime: nil)

            return UIImage(cgImage: cgImage)
        } catch {
            print(error.localizedDescription)

            return nil
        }
    }
}

用法:

let image = someURL.generateThumbnail()

答案 6 :(得分:-1)

func saveImageDocumentDirectoryWithDate(tempImage:UIImage, block : @escaping (_ url: URL?) -> Void ){

    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

    let random : String =  randomString(length: 5)

    let fileURL = documentsDirectoryURL.appendingPathComponent(String(format:"CPImage%@.png",random))
    do { try tempImage.pngData()?.write(to: fileURL) }
    catch { block(nil) }
    block(fileURL)}