美文网首页音视频
iOS为视频添加滤镜并导出

iOS为视频添加滤镜并导出

作者: unravelW | 来源:发表于2020-04-21 13:56 被阅读0次

    在Core Image中,图像处理依赖于CIFilterCIImage这两个类,一个代表过滤器,一个代表输入和输出的图像。

    以下是对图像应用滤镜的基本代码

    import CoreImage

    let context = CIContext()                                          // 1

    let filter = CIFilter(name: "CISepiaTone")!                        // 2

    filter.setValue(0.8, forKey: kCIInputIntensityKey)

    let image = CIImage(contentsOfURL: myURL)                          // 3

    filter.setValue(image, forKey: kCIInputImageKey)

    let result = filter.outputImage!                                    // 4

    let cgImage = context.createCGImage(result, from: result.extent)    // 5

    1、注意CIContext是一个重量级对象,如果你需要创建应尽早创建,并在每次处理图像时重用他。

    2、CIFilter对象代表要应用的过滤器,可以为其参数提供值

    3、通过URL提供的CIImage对象代表要处理的图像,将它提供给过滤器作为参数

    4、filter.outputImage这里的CIImage并不代表图像添加了滤镜,而是一个"配方",这个配方指明了如何去创建一个对应添加滤镜后的图像。

    5、最后我们通过CIImage生成一个Core Graphics Image以便于我们展示及保存该图像

    为视频添加滤镜

    AVFoundation提供了一个叫AVVideoComposition的类。您可以使用AVVideoComposition对象在回放或导出过程中将CIFilter应用于视频的每一帧。

    let filter = CIFilter(name: ciFilterName)!

    let composition =AVVideoComposition(asset: player.currentItem!.asset, applyingCIFiltersWithHandler: {  request in

                filter.setDefaults()

                filter.setValue(request.sourceImage, forKey:kCIInputImageKey)

                let output = filter.outputImage

                // Provide the filter output to the composition

                request.finish(with: output!, context:nil)

    })

    当你通过videoCompositionWithAsset:applyingCIFiltersWithHandler:这个初始化方法创建AVVideoComposition对象时,提供了一个handler来将过滤器加到每一帧画面上。 在播放或导出期间,AVFoundation会自动调用handler来处理图像。在handler中,通过AVAsynchronousCIImageFilteringRequest来获取每一帧图像来添加滤镜,然后提供过滤后的图像以供合成使用。

    player.currentItem?.videoComposition = composition 

     /*在播放中,我们将AVVideoComposition对象赋值给player.currentItem.videoComposition便可播放加滤镜后的视频。*/

    exportSession.videoComposition = player.currentItem?.videoComposition  

    /*在导出视频过程中将AVVideoComposition对象赋值给exportSession.videoComposition便可导出加滤镜后的视频。*/

    代码地址:https://github.com/JianBinWu/SWSwiftPractice

    GIF图演示:

    参考资料:https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_tasks/ci_tasks.html

    https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP40004346

    相关文章

      网友评论

        本文标题:iOS为视频添加滤镜并导出

        本文链接:https://www.haomeiwen.com/subject/ryquihtx.html