从视频提取缩略图时获取黑色空白图像

时间:2019-03-22 12:51:50

标签: ios swift

我正在尝试使用AVFoundation从URL的视频中获取缩略图,但是附件却出现了黑色空白图像。

视频URL为https://www.riptide.tv/app/assets/2/3/small_3001190658061_2.mp4

下面是我的代码:

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

        let asset = AVAsset(url: URL(string: videoURL)!)
        let assetImgGenerate = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true
    let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
        do {
            let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
            let thumbnail = UIImage(cgImage: img)
            downloadedThumbnails.updateValue(thumbnail, forKey: imgName)
            return thumbnail
        } catch {
            return UIImage(named: imgName)
        }
}

black img extracted

1 个答案:

答案 0 :(得分:0)

如果您将代码更改为

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

    let asset = AVAsset(url: URL(string: videoURL)!)
    let assetImgGenerate = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    let time = CMTimeMakeWithSeconds(Float64(5), preferredTimescale: 100)
    do {
        let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        let thumbnail = UIImage(cgImage: img)
        return thumbnail
    } catch {
        return UIImage(named: imgName)
    }
}

那是5秒钟。您可以看到生成的缩略图。

Thumbnail

这是因为AVAssetImageGenerator在什么时候获取帧都非常灵活

func videoSnapshot(videoURL: String, imgName : String) -> UIImage? {

    let asset = AVAsset(url: URL(string: videoURL)!)
    let assetImgGenerate = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.requestedTimeToleranceAfter = .zero
    assetImgGenerate.requestedTimeToleranceBefore = .zero
    let time = CMTimeMakeWithSeconds(Float64(1), preferredTimescale: 100)
    do {
        let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        let thumbnail = UIImage(cgImage: img)
        return thumbnail
    } catch {
        return UIImage(named: imgName)
    }
}

设置

assetImgGenerate.requestedTimeToleranceAfter = .zero
assetImgGenerate.requestedTimeToleranceBefore = .zero

确保获得准确的帧缩略图。

有关更多信息,请参见https://developer.apple.com/documentation/avfoundation/avassetimagegenerator/1390571-requestedtimetolerancebefore