1 #import2 #import 3 4 @interface UIImage (TY_ImageEditP) 5 /** 6 * 对图片进行模糊 7 * 8 * @param image 要处理图片 9 * @param blur 模糊系数 (0.0-1.0)10 *11 * @return 处理后的图片12 */13 + (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur;14 15 @end
1 #import "UIImage+TY_ImageEditP.h" 2 3 @implementation UIImage (TY_ImageEditP) 4 + (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur { 5 if (!image) { 6 return nil; 7 } 8 if ((blur < 0.0f) || (blur > 1.0f)) { 9 blur = 0.5f;10 }11 12 int boxSize = (int)(blur * 200);13 boxSize -= (boxSize % 2) + 1;14 15 CGImageRef img = image.CGImage;16 17 vImage_Buffer inBuffer, outBuffer;18 vImage_Error error;19 void *pixelBuffer;20 21 CGDataProviderRef inProvider = CGImageGetDataProvider(img);22 CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);23 24 inBuffer.width = CGImageGetWidth(img);25 inBuffer.height = CGImageGetHeight(img);26 inBuffer.rowBytes = CGImageGetBytesPerRow(img);27 inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);28 29 pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));30 31 outBuffer.data = pixelBuffer;32 outBuffer.width = CGImageGetWidth(img);33 outBuffer.height = CGImageGetHeight(img);34 outBuffer.rowBytes = CGImageGetBytesPerRow(img);35 36 error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL,37 0, 0, boxSize, boxSize, NULL,38 kvImageEdgeExtend);39 40 41 if (error) {42 NSLog(@"error from convolution %ld", error);43 }44 45 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();46 CGContextRef ctx = CGBitmapContextCreate(47 outBuffer.data,48 outBuffer.width,49 outBuffer.height,50 8,51 outBuffer.rowBytes,52 colorSpace,53 CGImageGetBitmapInfo(image.CGImage));54 55 CGImageRef imageRef = CGBitmapContextCreateImage (ctx);56 UIImage *returnImage = [UIImage imageWithCGImage:imageRef];57 58 //clean up59 CGContextRelease(ctx);60 CGColorSpaceRelease(colorSpace);61 62 free(pixelBuffer);63 CFRelease(inBitmapData);64 65 CGColorSpaceRelease(colorSpace);66 CGImageRelease(imageRef);67 68 return returnImage;69 }70 71 @end
例子~:
1 __weak typeof(self) weakSelf = self;2 [self.myImageView sd_setImageWithURL:[NSURL URLWithString:[ZLModel checkImageUrlNsstring:myModel.address withHttp:TY_IMAGEURL]] placeholderImage:[UIImage imageNamed:consultDefault] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {3 //毛玻璃效果处理4 UIImage *imageN = [UIImage blurryImage:image withBlurLevel:0.2];5 weakSelf.imageN = imageN;6 self.myImageView.image = self.imageN;7 8 }];