iOS滤镜

//对静态图像进行模糊处理

-(UIImage*)blurImage:(CGImageRef)srcImg{

//创建CIContext,这里关闭colormanagement有助于提升性能

NSDictionary*options=@{kCIContextWorkingColorSpace:[NSNullnull]};

CIContext*mContext=[CIContextcontextWithOptions:options];

CIImage*mImg=[[CIImagealloc]initWithCGImage:srcImg];

//创建高斯模糊滤镜,ios只支持这1种模糊滤镜,并且要ios6.0以上才行,inputRadius最大100,默认10

CIFilter*mBlurFilter=[CIFilterfilterWithName:@"CIGaussianBlur"];

[mBlurFiltersetValue:mImgforKey:kCIInputImageKey];

[mBlurFiltersetValue:@(10.0f)forKey:@"inputRadius”];

CIImage*mBlurImg=[mBlurFiltervalueForKey:kCIOutputImageKey];

CGImageRefmResultCGImg=[mContextcreateCGImage:mBlurImgfromRect:[mBlurImgextent]];

UIImage*mResultUIImg=[UIImageimageWithCGImage:mResultCGImg];

CGImageRelease(mDestImg);

[mImgrelease];

returnmResultUIImg;

}

//对摄像头作模糊处理

//使用AVFoundation实现摄像头功能并且实现AVCaptureVideoDataOutputSampleBufferDelegate托管协议

-(void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputSampleBuffer:(CMSampleBufferRef)sampleBufferfromConnection:(AVCaptureConnection*)connection{

CVImageBufferRefimageBuffer=CMSampleBufferGetImageBuffer(sampleBuffer);

CVPixelBufferLockBaseAddress(imageBuffer,0);

void*baseAddress=CVPixelBufferGetBaseAddress(imageBuffer);

size_tbytesPerRow=CVPixelBufferGetBytesPerRow(imageBuffer);

size_twidth=CVPixelBufferGetWidth(imageBuffer);

size_theight=CVPixelBufferGetHeight(imageBuffer);

staticCGColorSpaceRefcolorSpace=nil;

if(colorSpace==nil){

colorSpace=CGColorSpaceCreateDeviceRGB();

}

CGContextRefcontext=CGBitmapContextCreate(baseAddress,width,height,8,bytesPerRow,colorSpace,kCGBitmapByteOrder32Little|kCGImageAlphaPremultipliedFirst);

CGImageRefquartzImage=CGBitmapContextCreateImage(context);

//处理原始图像

UIImage*resultUIImage=[selfblurImage:quartzImage];

//更新某个UIImageView的image(隐藏摄像头的layer,盖一个UIImageView来播放滤镜处理后的图像)

...

CGImageRelease(quartzImage);

CGContextRelease(context);

CVPixelBufferUnlockBaseAddress(imageBuffer,0);

}

参考:

1.CoreImageProgrammingGuide

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_performance/ci_performance.html#//apple_ref/doc/uid/TP30001185-CH10-SW2

2.CoreImageFilterReference

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/uid/TP40004346

相关推荐