使用CoreImage为本地视频添加滤镜

本文简单介绍使用CoreImage提供的CIFilter为本地视频添加滤镜并导出视频到本地的操作

直接贴代码

导入头文件

#import "AVFoundation/AVFoundation.h"

-(void)exportClick{

 AVAsset *videoAsset = [AVURLAsset URLAssetWithURL:_filePath options:nil];//_filePath本地视频路径

CIFilter *filter = [CIFilter filterWithName:@"CIColorInvert"];

 AVVideoComposition *composition = [AVVideoComposition videoCompositionWithAsset:videoAsset applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {

        NSLog(@"导出中");//针对每一帧的图像做滤镜处理

        CIImage*source = request.sourceImage;

        [filtersetValue:sourceforKey:@"inputImage"];

        CIImage*resultImage = [filtervalueForKey:@"outputImage"];

        [requestfinishWithImage:resultImagecontext:nil];

    }];


    AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:videoAsset presetName:AVAssetExportPresetMediumQuality];

    exporter.videoComposition= composition ;

    exporter.outputURL = [NSURL fileURLWithPath:[self fileSavePathWithFileName:@"test"]];

    exporter.shouldOptimizeForNetworkUse = YES;

    exporter.outputFileType = AVFileTypeQuickTimeMovie;

    [exporterexportAsynchronouslyWithCompletionHandler:^{

        switch(exporter.status) {

            case AVAssetExportSessionStatusFailed:

                NSLog(@"exporting failed %@",[exportererror]);

                break;

            case AVAssetExportSessionStatusCompleted:

                NSLog(@"导出完成");

                break;

            case AVAssetExportSessionStatusCancelled:

                NSLog(@"export cancelled");

                break;

            case AVAssetExportSessionStatusUnknown:


                break;

            case AVAssetExportSessionStatusWaiting:


                break;

            case AVAssetExportSessionStatusExporting:


                break;

        }

    }];

}

//视频存放路径

-(NSString*)fileSavePathWithFileName:(NSString*)fileName{


    NSFileManager* fileManager = [NSFileManager defaultManager];


    NSString*filePath = [NSStringstringWithFormat:@"%@/Vidio/%@.mp4",DOCUMENTPATH,fileName];//视频存放位置

    NSString *folderPath = [NSString stringWithFormat:@"%@/Vidio", DOCUMENTPATH];

    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:filePath];

    if(blHave) {

        BOOLblDele= [fileManagerremoveItemAtPath:filePatherror:nil];

        if(!blDele) {

            [fileManagerremoveItemAtPath:filePatherror:nil];

        }

    }

    //判断视频存放文件夹是否存在,不存在创建

    BOOL blHave1=[[NSFileManager defaultManager] fileExistsAtPath:folderPath];

    if(!blHave1) {

        [fileManagercreateDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];

    }




    NSLog(@"视频输出地址 fileSavePath = %@",filePath);


    returnfilePath;

}


github地址:https://github.com/duchengdong/CIFilter

以上~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容