建议CocoaPods导入GPUImage类库,引入头文件即可使用:
#import "GPUImage.h"
视频实时滤镜
_stillCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
_stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
_stillCamera.frameRate = 30;
_stillCamera.horizontallyMirrorFrontFacingCamera = NO;
_filter = [[GPUImageBrightnessFilter alloc] init];
_filter.brightness=0.0;
GPUImageView *filteredVideoView = [[GPUImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, viewWidth, viewHeight)];
filteredVideoView.fillMode =kGPUImageFillModePreserveAspectRatioAndFill;
[self.view insertSubview:filteredVideoView atIndex:0];
/*
*视频实时滤镜(从camera获取经过_filter显示到filteredVideoView)
*/
[_stillCamera addTarget:_filter];
[_filter addTarget:filteredVideoView];
视频的写入
/*
*moveWriter用来记录保存视频
*/
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]);
self.movieURL = [NSURL fileURLWithPath:pathToMovie];
self.moveWriter =[[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:CGSizeMake(640.0, 480.0)];
[_filter addTarget:self.moveWriter]; //(经过_filter传给moveWriter)
self.moveWriter.encodingLiveVideo = YES;
_stillCamera.audioEncodingTarget = _moveWriter; //_moveWriter处理音频流
[_stillCamera startCameraCapture]; //开始捕获画面
图片捕获与过滤
[_stillCamera capturePhotoAsImageProcessedUpToFilter:_filter withCompletionHandler:^(UIImage *processedImage, NSError *error) {
NSData *dataForJPEGFile = UIImageJPEGRepresentation(processedImage, 0.8);
UIImage *image=[[UIImage alloc]initWithData:dataForJPEGFile];
//保存到沙盒document下
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSError *error2 = nil;
// if (![dataForJPEGFile writeToFile:[documentsDirectory stringByAppendingPathComponent:@"FilteredPhoto.jpg"] options:NSAtomicWrite error:&error2])
// {
// return;
// }
//保存到相册
// __block NSString *createdAssetID =nil;//唯一标识,可以用于图片资源获取
// NSError *myError =nil;
// [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
// createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
// } error:&myError];
self.photoImage=image;
self.type=ShowTypeImage;
[self performSegueWithIdentifier:@"show" sender:nil];
}];
图片滤镜
- (UIImage *)applyFilter:(GPUImageFilter *)filter
{
/*
*滤镜一张图片
*/
[filter forceProcessingAtSize:self.imageView.image.size];
[_pic removeAllTargets];
[_pic addTarget:filter];
[_pic processImage];
[filter useNextFrameForImageCapture];
return [filter imageFromCurrentFramebuffer];
}
//假若只需要对一张图片进行单一滤镜的话,可以这样写:
GPUImageSepiaFilter *stillImageFilter2 = [[GPUImageSepiaFilter alloc] init];
UIImage *quickFilteredImage = [stillImageFilter2 imageByFilteringImage:inputImage];
本地视频滤镜及保存
movieFile = [[GPUImageMovie alloc] initWithURL:sampleURL];
pixellateFilter = [[GPUImagePixellateFilter alloc] init];
[movieFile addTarget:pixellateFilter];
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]);
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0)];
[pixellateFilter addTarget:movieWriter];
movieWriter.shouldPassthroughAudio = YES;
movieFile.audioEncodingTarget = movieWriter;
[movieFile enableSynchronizedEncodingUsingMovieWriter:movieWriter];
[movieWriter startRecording];
[movieFile startProcessing];``
//记录结束时,需要把movieWriter从滤镜中移除,并且关闭它:
[pixellateFilter removeTarget:movieWriter];
[movieWriter finishRecording];
自定义滤镜
此类库相比系统Core Image 的一个重要优势就是能够自定义Filter,这些Filters需要创建Shader着色器,例如:
varying highp vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
lowp vec4 outputColor;
outputColor.r = (textureColor.r * 0.393) + (textureColor.g * 0.769) + (textureColor.b * 0.189);
outputColor.g = (textureColor.r * 0.349) + (textureColor.g * 0.686) + (textureColor.b * 0.168);
outputColor.b = (textureColor.r * 0.272) + (textureColor.g * 0.534) + (textureColor.b * 0.131);
outputColor.a = 1.0;
gl_FragColor = outputColor;
}
常遇到的问题
- 显示视频的View,要用GPUImageView
- 视频路径问题,例如:
NSURL* url = [NSURL fileURLWithPath:filePath], //正确 [NSURL URLWithString:filePath] //错误
- 提示Cannot call method when status is xx
status状态有:
typedef NS_ENUM(NSInteger, AVAssetWriterStatus) { AVAssetWriterStatusUnknown = 0, AVAssetWriterStatusWriting, AVAssetWriterStatusCompleted, AVAssetWriterStatusFailed, AVAssetWriterStatusCancelled };
当xx为2时,代表已完成一次文件写入,解决方案:
创建新的GPUImageMovieWriter
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (self.presentedViewController != nil) {
[self resetMovieWriter];
}
}
-(void)prepareWriter
{
/*
*moveWriter用来记录保存视频
*/
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]); // If a file already exists, AVAssetWriter won't let you record new frames, so delete the old movie
self.movieURL = [NSURL fileURLWithPath:pathToMovie];
self.moveWriter =[[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:CGSizeMake(640.0, 480.0)];
[_filter addTarget:self.moveWriter]; //(经过_filter传给moveWriter)
self.moveWriter.encodingLiveVideo = YES;
_stillCamera.audioEncodingTarget = _moveWriter; //_moveWriter处理音频流
[_stillCamera startCameraCapture]; //捕获画面
}
当xx为3时,代表文件路径已存在,解决方案:
//1.删除已存在文件
unlink([pathToMovie UTF8String])
//2.重新生成新目录
//[_currentVideoPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lld.mp4", (long long)[[NSDate date] timeIntervalSince1970]]]