拍照的时候象让相机有一些滤镜效果,通过GPUImage可以很容易的实现
前戏
1.这里需要一个第三方的开源框架,用的你的pod 直接倒入
target 'xxx' do
pod 'GPUImage'
end
2.然后在你的工程里导入相应的头文件
#import <GPUImage.h>
#import <AssetsLibrary/AssetsLibrary.h>
//存储图片的 iOS 9.0以后需要导入#import <Photos/Photos.h>,相应的方法 自行查阅
3.需要的几个类
@property (nonatomic, strong) GPUImageStillCamera *camera;
@property (nonatomic, strong) GPUImageFilter *filter;//?< 滤镜
@property (nonatomic, strong) GPUImageView *imageView;//?< 展示camera的view
4.别忘记获得相机 和 相册的权限,在info.plist里添加
相机权限: Privacy - Camera Usage Description 是否允许此App使用你的相机?
相册权限: Privacy - Photo Library Usage Description 是否允许此App访问你的媒体资料库
进入正题
self.camera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
self.camera.outputImageOrientation = UIInterfaceOrientationPortrait;
self.camera.horizontallyMirrorFrontFacingCamera = YES;
//滤镜 创建, 这个滤镜是黑白的效果 还有很多 自己去看
self.filter = [[GPUImageSketchFilter alloc] init];
//创建展示相机的视图
self.imageView = [[GPUImageView alloc] initWithFrame:self.view.bounds];
self.imageView.center = self.view.center;
[self.view addSubview:self.imageView];
//这里一定要注意 一定要先加滤镜->在加视图->然后吧camera开始获取视频图像
[self.camera addTarget:self.filter];
[self.filter addTarget:self.imageView];
//开始获取视频
[self.camera startCameraCapture];
//按钮拍照
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((self.view.bounds.size.width-80)*0.5, self.view.bounds.size.height-60, 80, 40)];
button.backgroundColor = [UIColor blueColor];
[button setTitle:@"点击拍照" forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(takePhotoToAlbum) forControlEvents:UIControlEventTouchUpInside];
- (void)takePhotoToAlbum
{
[self.camera capturePhotoAsJPEGProcessedUpToFilter:self.filter withCompletionHandler:^(NSData *processedJPEG, NSError *error) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageDataToSavedPhotosAlbum:processedJPEG metadata:_camera.currentCaptureMetadata completionBlock:^(NSURL *assetURL, NSError *error2)
{
if (error2) {
NSLog(@"ERROR: the image failed to be written");
}
else {
NSLog(@"PHOTO SAVED - assetURL: %@", assetURL);
}
}];
}];
}