微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从返回相同图像的视频创建UIImage数组-快速-以编程方式

如何解决从返回相同图像的视频创建UIImage数组-快速-以编程方式

我正在从视频中检索一些UIImage,并将它们存储在数组中。

fileprivate func createImageFramesFromVideo(urlVideoPassed: URL,completion: @escaping ([UIImage]) -> Void) {
    let finalAsset = AVAsset(url: urlVideoPassed)
    let imageGenerator = AVAssetimageGenerator(asset: finalAsset)
    let videoDuration = asset!.duration
    
    //getting image snapshots more or less in half the video
    
    
    let time1 = CMTimeMakeWithSeconds(videoDuration.seconds/2-(videoDuration.seconds*0.3),preferredTimescale: videoDuration.timescale)
    let time2 = CMTimeMakeWithSeconds(videoDuration.seconds/2-(videoDuration.seconds*0.2),preferredTimescale: videoDuration.timescale)
    let time3 = CMTimeMakeWithSeconds(videoDuration.seconds/2-(videoDuration.seconds*0.1),preferredTimescale: videoDuration.timescale)
    let time4 = CMTimeMakeWithSeconds(videoDuration.seconds/2,preferredTimescale: videoDuration.timescale)
    
    let time5 = CMTimeMakeWithSeconds(videoDuration.seconds/2+(videoDuration.seconds*0.1),preferredTimescale: videoDuration.timescale)
    let time6 = CMTimeMakeWithSeconds(videoDuration.seconds/2+(videoDuration.seconds*0.2),preferredTimescale: videoDuration.timescale)
    let time7 = CMTimeMakeWithSeconds(videoDuration.seconds/2+(videoDuration.seconds*0.3),preferredTimescale: videoDuration.timescale)
    
    let times = [NSValue(time: time1),NSValue(time: time2),NSValue(time: time3),NSValue(time: time4),NSValue(time: time5),NSValue(time: time6),NSValue(time: time7)]
    
    var imageArray : [UIImage] = []
    
    let dispatchGroup = dispatchGroup()
    times.forEach { _ in
        dispatchGroup.enter()
    }
    
    imageGenerator.generateCGImagesAsynchronously(forTimes: times) { (time,image,time1,result,err) in
        if let err = err {
            print("there's an error in retrieving the images",err)
        }
        
        guard let imagetopass = image else {
            return
        }
        
        let theImage = UIImage(cgImage: imagetopass)
        
        imageArray.append(theImage)
        
        dispatchGroup.leave()
    }
    
    //when all images are retrieved,passes them to completion block
    dispatchGroup.notify(queue: .main) {
        completion(imageArray)
    }
}

问题在于时间戳:

let time3 = CMTimeMakeWithSeconds(videoDuration.seconds/2-(videoDuration.seconds*0.1),preferredTimescale: videoDuration.timescale)

let time5 = CMTimeMakeWithSeconds(videoDuration.seconds/2+(videoDuration.seconds*0.1),preferredTimescale: videoDuration.timescale)

即使在某种情况下我增加了一些时间,在另一种情况下我减去了它,我也会检索同一帧。对于其他所有具有相反符号的帧,也会发生这种情况。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。