9

In my iPhone application I have a black-and-white UIImage. I need to blur that image (Gaussian blur would do).

iPhone clearly knows how to blur images, as it does that when it draws shadows.

However I did not found anything related in the API.

Do I have to do blurring by hand, without hardware acceleration?

Alexander Gladysh
  • 39,865
  • 32
  • 103
  • 160

5 Answers5

15

Try this (found here):

@interface UIImage (ImageBlur)
- (UIImage *)imageWithGaussianBlur;
@end

@implementation UIImage (ImageBlur)
- (UIImage *)imageWithGaussianBlur {
    float weight[5] = {0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162};
    // Blur horizontally
    UIGraphicsBeginImageContext(self.size);
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[0]];
    for (int x = 1; x < 5; ++x) {
        [self drawInRect:CGRectMake(x, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[x]];
        [self drawInRect:CGRectMake(-x, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[x]];
    }
    UIImage *horizBlurredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // Blur vertically
    UIGraphicsBeginImageContext(self.size);
    [horizBlurredImage drawInRect:CGRectMake(0, 0, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[0]];
    for (int y = 1; y < 5; ++y) {
        [horizBlurredImage drawInRect:CGRectMake(0, y, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[y]];
        [horizBlurredImage drawInRect:CGRectMake(0, -y, self.size.width, self.size.height) blendMode:kCGBlendModePlusLighter alpha:weight[y]];
    }
    UIImage *blurredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //
    return blurredImage;
}

And use it like this:

UIImage *blurredImage = [originalImage imageWithGaussianBlur];

To get stronger blur just apply this effect twice or more :)

Community
  • 1
  • 1
dom
  • 11,894
  • 10
  • 51
  • 74
6

After having the same problem by the past, check this lib:

https://github.com/tomsoft1/StackBluriOS

Very easy to use also:

UIImage *newIma=[oldIma stackBlur:radius];
tomsoft
  • 4,448
  • 5
  • 28
  • 35
2

Consider approaching the job via CIFilter:

Developing Core Image Filters for iOS

waterforest
  • 154
  • 1
  • 8
0

Basically there is no a straight forward API to implement the blur effect. You need to process the pixels to accomplish that.

iPhone draw shadows by means of gradient and not through blurring.

GeneCode
  • 7,545
  • 8
  • 50
  • 85
0

To blur an image, you would use a convolution matrix. Here is the sample code to apply a convolution matrix, and here is an overview of convolution matrices as well as some sample matrices (including blur and gaussian blur).

Community
  • 1
  • 1
Mirkules
  • 1,709
  • 15
  • 21