且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

高斯模糊图像 - iOS 8

更新时间:2023-02-26 20:43:20

我根据您的照片做了一个小例子。我的算法如下:

I have done a small example based on the photo you have there. My algorithm is as follows:


  • 从底部提取一部分图像。

  • 应用高斯滤波器

  • 然后,创建一个新的图像上下文,在其上绘制原始图像。

  • 然后,绘制模糊部分将图像精确地放在原始图像上。

  • 从上下文中提取新图像。

  • Extract a portion of image from bottom.
  • Apply gaussian filter to it and blur it.
  • Then, create a new image context, draw original image on it.
  • Then, draw the blurred portion of the image to place it exactly over the original image.
  • Extract the new image from the context.

这是这样做的源代码,

 @implementation ViewController


- (void)viewDidLoad{

  [super viewDidLoad];
  UIImageView *imageView = [[UIImageView alloc] init];
  imageView.frame = self.view.bounds;
  [self.view  addSubview:imageView];
  imageView.contentMode = UIViewContentModeScaleAspectFit;
  UIImage *image = [UIImage imageNamed:@"monogram.jpg"];
  imageView.image = [self imageWithBlurredImageWithImage: image andBlurInsetFromBottom: 200 withBlurRadius:3];
}

- (UIImage*)imageWithBlurredImageWithImage:(UIImage*)image andBlurInsetFromBottom:(CGFloat)bottom withBlurRadius:(CGFloat)blurRadius{
  UIGraphicsBeginImageContext(image.size);
  CGContextRef context =  UIGraphicsGetCurrentContext();
  CGContextScaleCTM(context, 1, -1);
  CGContextTranslateCTM(context, 0, -image.size.height);
  CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
  CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, bottom), [self blurImage: image withBottomInset: bottom blurRadius: blurRadius].CGImage);
  image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image;
}

- (UIImage*)blurImage:(UIImage*)image withBottomInset:(CGFloat)inset blurRadius:(CGFloat)radius{

  image =  [UIImage imageWithCGImage: CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, image.size.height - inset, image.size.width,inset))];

  CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
  CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
  [filter setValue:ciImage forKey:kCIInputImageKey];
  [filter setValue:@(radius) forKey:kCIInputRadiusKey];

  CIImage *outputCIImage = filter.outputImage;
  CIContext *context = [CIContext contextWithOptions:nil];

  return [UIImage imageWithCGImage: [context createCGImage:outputCIImage fromRect:ciImage.extent]];

}
@end

这是截图结果。