iOS 视频添加滤镜效果

为视频添加滤镜效果的思路如下
1.使用AVPlayer + CIFilter进行渲染

参考文档 Processing Video with AV Foundation

关键代码

//1
AVURLAsset *asset1 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sample_clip1" ofType:@"m4v"]]];

//2
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
AVVideoComposition *composition1 = [AVVideoComposition videoCompositionWithAsset:asset1 applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
//3
    CIImage *source = request.sourceImage.imageByClampingToExtent;
    int currentTime = request.compositionTime.value / request.compositionTime.timescale;
    if (currentTime < 3) {
        [request finishWithImage:source context:nil];
    } else {
        [filter setValue:source forKey:kCIInputImageKey];
//4
        CIImage *output = [filter.outputImage imageByCroppingToRect:request.sourceImage.extent];
        [request finishWithImage:output context:nil];
    }
}];

//5
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset1];
item.videoComposition = composition;

步骤1:读取本地的视频路径
步骤2:设置CIFilter效果,使用AVVideoComposition处理渲染过程
步骤3:获取视频帧并转换成CIImage以供CIFilter进行渲染,可以设定渲染的时间
步骤4:将渲染完成的CIImage返还给request
步骤5:将视频组成装入播放文件中播放即可

存在问题:
1.播放与导出时加入滤镜的情况下cpu占用100%

实例参见 github Demo

你可能感兴趣的:(iOS 视频添加滤镜效果)