美文网首页TempUI效果
iOS 图片添加高斯模糊

iOS 图片添加高斯模糊

作者: JamesGu0116 | 来源:发表于2016-03-20 00:55 被阅读322次

    在之前公司有个项目中高斯模糊效果没做,大晚上,想了想,还是补上吧。

    
    记得添加Accelerate类库并import
    #import <Accelerate/Accelerate.h>
    
    
    /**
     *  图片添加高斯模糊效果
     *
     *  @param image 原始图片
     *  @param blur  高斯模糊等级
     *
     *  @return 添加高斯模糊后的图片
     */
    - (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
        if ((blur < 0.0f) || (blur > 1.0f)) {
            blur = 0.5f;
        }
        
        int boxSize = (int)(blur * 100);
        boxSize -= (boxSize % 2) + 1;
        
        CGImageRef img = image.CGImage;
        
        vImage_Buffer inBuffer, outBuffer;
        vImage_Error error;
        void *pixelBuffer;
        
        CGDataProviderRef inProvider = CGImageGetDataProvider(img);
        CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
        
        inBuffer.width = CGImageGetWidth(img);
        inBuffer.height = CGImageGetHeight(img);
        inBuffer.rowBytes = CGImageGetBytesPerRow(img);
        inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
        
        pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
        
        outBuffer.data = pixelBuffer;
        outBuffer.width = CGImageGetWidth(img);
        outBuffer.height = CGImageGetHeight(img);
        outBuffer.rowBytes = CGImageGetBytesPerRow(img);
        
        error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL,
                                           0, 0, boxSize, boxSize, NULL,
                                           kvImageEdgeExtend);
        
        if (error) {
            NSLog(@"error from convolution %ld", error);
        }
        
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef ctx = CGBitmapContextCreate(
                                                 outBuffer.data,
                                                 outBuffer.width,
                                                 outBuffer.height,
                                                 8,
                                                 outBuffer.rowBytes,
                                                 colorSpace,
                                                 CGImageGetBitmapInfo(image.CGImage));
        
        CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
        UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
        
        CGContextRelease(ctx);
        CGColorSpaceRelease(colorSpace);
        
        free(pixelBuffer);
        CFRelease(inBitmapData);
        
        CGImageRelease(imageRef);
        
        return returnImage;
    }
    
    

    相关文章

      网友评论

      • 记忆淡忘中:我想不懂为什么我添加高斯模糊图片也有模糊效果 但是变成蓝色了

      本文标题:iOS 图片添加高斯模糊

      本文链接:https://www.haomeiwen.com/subject/hxohlttx.html