iOS实现高斯模糊效果(Swift版本)
给UIimage添加分类
1 extension UIImage { 2 /// 高斯模糊 3 func gaussianBlur(var blurAmount:CGFloat) -> UIImage { 4 //高斯模糊参数(0-1)之间,超出范围强行转成0.5 5 if (blurAmount < 0.0 || blurAmount > 1.0) { 6 blurAmount = 0.5 7 } 8 9 var boxSize = Int(blurAmount * 40) 10 boxSize = boxSize - (boxSize % 2) + 1 11 12 let img = self.CGImage 13 14 var inBuffer = vImage_Buffer() 15 var outBuffer = vImage_Buffer() 16 17 let inProvider = CGImageGetDataProvider(img) 18 let inBitmapData = CGDataProviderCopyData(inProvider) 19 20 inBuffer.width = vImagePixelCount(CGImageGetWidth(img)) 21 inBuffer.height = vImagePixelCount(CGImageGetHeight(img)) 22 inBuffer.rowBytes = CGImageGetBytesPerRow(img) 23 inBuffer.data = UnsafeMutablePointer<Void>(CFDataGetBytePtr(inBitmapData)) 24 25 //手动申请内存 26 let pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img)) 27 28 outBuffer.width = vImagePixelCount(CGImageGetWidth(img)) 29 outBuffer.height = vImagePixelCount(CGImageGetHeight(img)) 30 outBuffer.rowBytes = CGImageGetBytesPerRow(img) 31 outBuffer.data = pixelBuffer 32 33 var error = vImageBoxConvolve_ARGB8888(&inBuffer, 34 &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0), 35 UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend)) 36 if (kvImageNoError != error) 37 { 38 error = vImageBoxConvolve_ARGB8888(&inBuffer, 39 &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0), 40 UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend)) 41 if (kvImageNoError != error) 42 { 43 error = vImageBoxConvolve_ARGB8888(&inBuffer, 44 &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0), 45 UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend)) 46 } 47 } 48 49 let colorSpace = CGColorSpaceCreateDeviceRGB() 50 let ctx = CGBitmapContextCreate(outBuffer.data, 51 Int(outBuffer.width), 52 Int(outBuffer.height), 53 8, 54 outBuffer.rowBytes, 55 colorSpace, 56 CGImageAlphaInfo.PremultipliedLast.rawValue) 57 58 let imageRef = CGBitmapContextCreateImage(ctx) 59 60 //手动申请内存 61 free(pixelBuffer) 62 return UIImage(CGImage: imageRef!) 63 } 64 }
posted on 2017-04-11 23:41 wangtianze 阅读(2208) 评论(0) 编辑 收藏 举报