GPUImage滤镜

1、相机实时滤镜
@interface RealtimeImageFilterVC ()
{
    GPUImageView *primaryView;
    GPUImageStillCamera *stillCamera;
    GPUImageCropFilter *corpFilter;
    GPUImageOutput *filter; //滤镜
    CGFloat effectiveScale;
    CGFloat beginGestureScale;
}
@end

@implementation RealtimeImageFilterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    beginGestureScale = 1.0;
    
    //创建实时滤镜
    //生成展示区
    [self creatShowCameraView];
    //创建相机和滤镜层
    [self creatActiveDevice];
    //添加上边的视图
    [self topView];
    //添加下边的视图
    [self bottomView];
    
}
#pragma mark - 创建UI
//创建展示区
-(void)creatShowCameraView
{
    CGRect mainScreenFrame = [[UIScreen mainScreen] bounds];
    primaryView = [[GPUImageView alloc] initWithFrame:mainScreenFrame];
    primaryView.backgroundColor = [UIColor clearColor];
    primaryView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:primaryView];
}
#pragma mark - 创建功能项

-(void)creatActiveDevice
{
    //图片捕获
    stillCamera = [[GPUImageStillCamera alloc] init];
    stillCamera.captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
    stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    //镜头比例 默认为4:3 的比例
    corpFilter = [[GPUImageCropFilter alloc] initWithCropRegion:CGRectMake(0.f, 0.f, 1.0f, 1.0f)];
    //滤镜
    filter = [[GPUImageFilter alloc] init];
    [stillCamera addTarget:corpFilter];
    [corpFilter addTarget:filter];
    [filter addTarget:primaryView];
    
    [stillCamera startCameraCapture];
    
    //TODO: 初始化曝光模式 和 聚焦模式
//    if ([stillCamera.inputCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
//        [stillCamera.inputCamera lockForConfiguration:nil];
//        [stillCamera.inputCamera setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
//        [stillCamera.inputCamera unlockForConfiguration];
//    }
//    
//    if ([stillCamera.inputCamera isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
//        [stillCamera.inputCamera lockForConfiguration:nil];
//        [stillCamera.inputCamera setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
//        [stillCamera.inputCamera unlockForConfiguration];
//    }
//    [stillCamera.inputCamera lockForConfiguration:nil];
//    if ([stillCamera.inputCamera isFlashModeSupported:AVCaptureFlashModeOff]) {
//        [stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOff];
//    }
//    [stillCamera.inputCamera unlockForConfiguration];
    
    //滤镜处理对象
//    rsfilterAPI = [[RSFilterAPI alloc] init];
}
#pragma mark - 上部视图
- (void)topView{
    //打开闪关灯
    UIButton *lampButton = [UIButton buttonWithType:UIButtonTypeSystem];
    lampButton.frame = CGRectMake(0, 64, 100, 100);
    [lampButton setTitle:@"闪光灯切换" forState:UIControlStateNormal];
    [lampButton addTarget:self action:@selector(lanmpButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lampButton];
    //切换前后摄像头
    UIButton *lensButton = [UIButton buttonWithType:UIButtonTypeSystem];
    lensButton.frame = CGRectMake(120, 64, 100, 100);
    [lensButton setTitle:@"前后摄像头切换" forState:UIControlStateNormal];
    [lensButton addTarget:self action:@selector(lensButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lensButton];
    //添加网格
    UIButton *gridButton = [UIButton buttonWithType:UIButtonTypeSystem];
    gridButton.frame = CGRectMake(230, 64, 100, 100);
    [gridButton setTitle:@"添加网格线" forState:UIControlStateNormal];
    [gridButton addTarget:self action:@selector(gridButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:gridButton];
    //添加缩放手势
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] init];
    [pinch addTarget:self action:@selector(handlePinchGesture:)];
    [primaryView addGestureRecognizer:pinch];
}
#pragma mark - 闪光灯
- (void)lanmpButton{
    if ([stillCamera.inputCamera isFlashModeSupported:AVCaptureFlashModeOff]) {
        [stillCamera.inputCamera lockForConfiguration:nil];
        [stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOn];
        [stillCamera.inputCamera unlockForConfiguration];
    }
}
#pragma mark - 切换前后摄像头
- (void)lensButton{
    stillCamera.horizontallyMirrorFrontFacingCamera = YES;
    [stillCamera rotateCamera];
    //判断当前是前置还是后置摄像头
//    _currentCameraPosition = stillCamera.inputCamera.position;
//    if (_currentCameraPosition == AVCaptureDevicePositionFront)
}
#pragma mark - 添加网格线
- (void)gridButton{
    //太无聊,不实现
}
#pragma mark - 添加缩放手势
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)gesture{
    effectiveScale = beginGestureScale * gesture.scale;
    if (effectiveScale < 1.0)
        effectiveScale = 1.0;
    if (effectiveScale > 5)
        effectiveScale = 5;
    [CATransaction begin];
    
    if (effectiveScale > 5) {
        effectiveScale = 5;
    }else if (effectiveScale <1){
        effectiveScale = 1;
    }
    [stillCamera.inputCamera lockForConfiguration:nil];
    [stillCamera.inputCamera setVideoZoomFactor:effectiveScale];
    [stillCamera.inputCamera unlockForConfiguration];
    [CATransaction commit];
    
    if (gesture.state == UIGestureRecognizerStateEnded) {
        beginGestureScale = effectiveScale;
    }
}

#pragma mark - 下部视图
- (void)bottomView{
    //拍照按钮
    UIButton *tapButton = [UIButton buttonWithType:UIButtonTypeSystem];
    tapButton.frame = CGRectMake(100, self.view.frame.size.height - 49 - 50, 100, 50);
    [tapButton setTitle:@"拍照" forState:UIControlStateNormal];
    [self.view addSubview:tapButton];
    [tapButton addTarget:self action:@selector(tapButton) forControlEvents:UIControlEventTouchUpInside];
    //切换比例按钮
    UIButton *sizeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sizeButton.frame = CGRectMake(200, self.view.frame.size.height - 49 - 50, 100, 50);
    [sizeButton setTitle:@"切换比例" forState:UIControlStateNormal];
    [self.view addSubview:sizeButton];
    [sizeButton addTarget:self action:@selector(sizeButton) forControlEvents:UIControlEventTouchUpInside];
    //实时滤镜滚动条
    UIButton *filterButton = [UIButton buttonWithType:UIButtonTypeSystem];
    filterButton.frame = CGRectMake(100, self.view.frame.size.height - 49 - 50 - 50, 200, 50);
    [filterButton setTitle:@"颜色反转滤镜" forState:UIControlStateNormal];
    [self.view addSubview:filterButton];
    [filterButton addTarget:self action:@selector(filterButton) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 滤镜
- (void)filterButton{
    //第一步
    [stillCamera removeAllTargets];
    [filter removeAllTargets];
    //第二步
    filter = [[GPUImageColorInvertFilter alloc] init];
    
    [stillCamera addTarget:corpFilter];
    [corpFilter addTarget:filter];
    [filter addTarget:primaryView];
}
#pragma mark - 拍照按钮
- (void)tapButton{
    [stillCamera capturePhotoAsImageProcessedUpToFilter:filter withOrientation:UIImageOrientationUp withCompletionHandler:^(UIImage *processedImage, NSError *error) {
        ImageViewController *imageVC = [[ImageViewController alloc] init];
        imageVC.hidesBottomBarWhenPushed = YES;
        imageVC.filterImage = processedImage;
        [self.navigationController pushViewController:imageVC animated:YES];
    }];
}
#pragma mark - 切换比例按钮
- (void)sizeButton{
    //切换为1:1的比例
     corpFilter.cropRegion = CGRectMake(0.f, 0.125f, 1.0f, 0.75f);

}

2、图片滤镜处理

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *testImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 84,IPHONE_WIDTH - 40, IPHONE_WIDTH - 40)];
    testImage.backgroundColor = [UIColor redColor];
    testImage.contentMode = UIViewContentModeScaleAspectFit;
    testImage.clipsToBounds = YES;
    testImage.image = [UIImage imageNamed:@"imageTest"];
    [self.view addSubview:testImage];
    
    //初始化图片
    self.picture = [[GPUImagePicture alloc] initWithImage:[UIImage imageNamed:@"imageTest"]];
    //初始化滤镜
    self.filter = [[GPUImageSepiaFilter alloc] init];
    //像图片添加滤镜
    [self.picture addTarget:self.filter];
    //开始处理图片
    [self.filter useNextFrameForImageCapture];
    [self.picture processImage];
    
    testImage.image = [self.filter imageFromCurrentFramebuffer];
    
}

//_gpuImageView=[[GPUImageView alloc] init];
//
//    _sourcePicture=[[GPUImagePicture alloc] initWithImage:_sourceImage smoothlyScaleOutput:NO];
//    self.gpuFilter = [[RSFilterAPI alloc] init];
//
//    _customFilter=[self.gpuFilter getCustomFilter];
//    [_sourcePicture addTarget:_customFilter];
//    [_customFilter addTarget:_gpuImageView];


3、视频实时滤镜

- (void)creatRealTimeVideoFilter{
    self.videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
    self.videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    self.videoCamera.horizontallyMirrorFrontFacingCamera = YES;
    self.filterView = [[GPUImageView alloc] initWithFrame:self.view.frame];
    self.filterView.center = self.view.center;
    
    [self.view addSubview:self.filterView];
    
    self.filter = [[GPUImageBeautifyFilter alloc] init];
    [self.videoCamera addTarget:self.filter];
    [self.filter addTarget:self.filterView];
    //不使用滤镜
//    [self.videoCamera removeAllTargets];
//    [self.videoCamera addTarget:self.filterView];
    
    [self.videoCamera startCameraCapture];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 300, 50, 50);
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonTap:(UIButton *)button{
    button.selected = !button.selected;
    if (button.selected) {
        //开始保存视频
        NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
        unlink([pathToMovie UTF8String]);
        NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
        
        _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(640.0, 480.0)];
        self.videoCamera.audioEncodingTarget = _movieWriter;
        _movieWriter.encodingLiveVideo = YES;
        
        [self.filter addTarget:_movieWriter];
        [_movieWriter startRecording];
    }else{
        //保存完成
        [self.filter removeTarget:_movieWriter];
        [_movieWriter finishRecording];
    }
}

4、简单的视频添加滤镜

self.filterView = [[GPUImageView alloc] initWithFrame:self.view.frame];
    self.filterView.center = self.view.center;
    [self.view addSubview:self.filterView];
    
    // 播放 源视频
    NSURL *sampleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"]];
    self.movieFile = [[GPUImageMovie alloc] initWithURL:sampleURL];
    self.movieFile.runBenchmark = YES;
    self.movieFile.playAtActualSpeed = YES;
    [self.movieFile addTarget:self.filterView];
    [self.movieFile startProcessing];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 300, 50, 50);
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)buttonTap:(UIButton *)button{
    //取消播放
    [self.movieFile cancelProcessing];
    //取消滤镜
    [self.movieFile removeAllTargets];
    [self.filter removeAllTargets];
    self.filter = [[GPUImageSepiaFilter alloc] init];
    //添加滤镜
    [self.movieFile addTarget:self.filter];
    [self.filter addTarget:self.filterView];
    
    
    //视频重新编码
    NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Static.m4v"];
    unlink([pathToMovie UTF8String]);
    NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
    self.movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0)];
    [self.filter addTarget:self.movieWriter];
    
    self.movieWriter.shouldPassthroughAudio = YES;
    self.movieFile.audioEncodingTarget = self.movieWriter;
    [self.movieFile enableSynchronizedEncodingUsingMovieWriter:self.movieWriter];
    //开始录制
    [self.movieWriter startRecording];
    //开始播放
    [self.movieFile startProcessing];
    //录制完成
    __weak typeof(self) weakSelf = self;
    self.movieWriter.completionBlock = ^(){
        [weakSelf.filter removeAllTargets];
        [weakSelf.movieWriter finishRecording];
    };
}

DEMO下载地址:http://download.csdn.net/detail/huobanbengkui/9728696

参考资料:http://www.jianshu.com/p/856f30c86d2f



你可能感兴趣的:(iOS)