GPUImage实现实时滤镜

系统自带的AVFoundation框架以及Core Image可以帮助我们实现给图片加滤镜效果,但是如果我们需要给镜头加上实时滤镜的效果,就是我们通常用到的各种美颜相机等App的滤镜效果,可以用GPUImage来实现。所以首先,我们需要导入GPUImage。

可以用cocopods导入文件

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'Test' do
  # Uncomment this line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for Test
pod ‘GPUImage’
end

也可以在github上下载,如何拖入工程中
https://github.com/BradLarson/GPUImage/downloads

导入头文件

#import "GPUImage.h"

声明几个必要的属性

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;;//浏览图层

@property (nonatomic, strong) GPUImageStillCamera *imageCamera;
@property (nonatomic, strong) GPUImageView *filterView;
@property (nonatomic, strong) GPUImageFilter *filter;
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.delegate = nil;
    [super viewWillAppear:YES];

    if (self.imageCamera.captureSession) {
        [self.imageCamera.captureSession startRunning];
    }

}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];

    if (self.imageCamera.captureSession) {
        [self.imageCamera.captureSession stopRunning];
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    ///self.view.backgroundColor = [UIColor whiteColor];

       //初始化相机设备
    [self initCamera];

}

初始化相机

- (void)initCamera{
    _imageCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset1280x720 cameraPosition:AVCaptureDevicePositionBack];
    _imageCamera.outputImageOrientation = UIDeviceOrientationPortrait;
    _imageCamera.horizontallyMirrorFrontFacingCamera = YES;
    _imageCamera.horizontallyMirrorRearFacingCamera = NO;

    //更改这个设置的时候必须先锁定设备,修改完后再解锁,否则崩溃
    [_imageCamera.inputCamera lockForConfiguration:nil];
    //设置闪光灯为自动
    [_imageCamera.inputCamera unlockForConfiguration];

    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_imageCamera.captureSession];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    _previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.view.layer.masksToBounds = YES;
    [self.view.layer addSublayer:_previewLayer];

    [_imageCamera startCameraCapture];
}

需要说明一下,GPUImage中自带的滤镜效果有很多,你需要的只是将你要用的滤镜效果add到filterView上即可,在这里就用常用的卡通滤镜效果示范一下

 -(void)addFilter //添加滤镜
{
    _filter = [[GPUImageToonFilter alloc] init];
    [_filter addTarget:self.filterView];
    [self.imageCamera addTarget:self.filter];
}

完成以上操作,就可以看到已添加的实时滤镜效果,如果想要在此基础上实现拍摄功能,只需要

- (void)action_TakeShot:(UIButton *)sender{//button点击事件
    NSLog(@"------------- 拍照");
    [self.imageCamera capturePhotoAsImageProcessedUpToFilter:self.filter withCompletionHandler:^(UIImage *processedImage, NSError *error) {
        //processedImage即为拍下的带有滤镜效果的照片
    }];

}

需要注意的是,GPUImage中封装了GPUImageStillCamera和GPUImageVideoCamera等相机,都可以实现实时滤镜,但是实现拍照功能的相机,推荐使用GPUImageStillCamera,想要实现摄影功能,推荐使用GPUImageVideoCamera,有时间再多研究一下,感觉GPUImage挺强大的

你可能感兴趣的:(学习)