Last active
November 30, 2023 14:26
-
-
Save ericdke/fae887759c2fe9748efb to your computer and use it in GitHub Desktop.
Swift: blur an UIImage with the Accelerate framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| import XCPlayground | |
| import Accelerate | |
| extension UIImage { | |
| public func blur(size: Float) -> UIImage! { | |
| let boxSize = size - (size % 2) + 1 | |
| let image = self.CGImage | |
| let inProvider = CGImageGetDataProvider(image) | |
| let height = vImagePixelCount(CGImageGetHeight(image)) | |
| let width = vImagePixelCount(CGImageGetWidth(image)) | |
| let rowBytes = CGImageGetBytesPerRow(image) | |
| let inBitmapData = CGDataProviderCopyData(inProvider) | |
| let inData = UnsafeMutablePointer<Void>(CFDataGetBytePtr(inBitmapData)) | |
| var inBuffer = vImage_Buffer(data: inData, height: height, width: width, rowBytes: rowBytes) | |
| let outData = malloc(CGImageGetBytesPerRow(image) * CGImageGetHeight(image)) | |
| var outBuffer = vImage_Buffer(data: outData, height: height, width: width, rowBytes: rowBytes) | |
| let _ = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend)) | |
| let colorSpace = CGColorSpaceCreateDeviceRGB() | |
| let context = CGBitmapContextCreate(outBuffer.data, Int(outBuffer.width), Int(outBuffer.height), 8, outBuffer.rowBytes, colorSpace, CGImageGetBitmapInfo(image).rawValue) | |
| let imageRef = CGBitmapContextCreateImage(context)! | |
| let bluredImage = UIImage(CGImage: imageRef) | |
| free(outData) | |
| return bluredImage | |
| } | |
| } | |
| let img = [#Image(imageLiteral: "conv.jpg")#] | |
| let orig = UIImageView(image: img) | |
| let blurred = img.blur(50) | |
| let o = UIImageView(frame: CGRect(x: 0, y: 0, width: orig.frame.width, height: orig.frame.height)) | |
| o.image = img | |
| let v = UIImageView(frame: CGRect(x: 0, y: orig.frame.height, width: orig.frame.width, height: orig.frame.height)) | |
| v.image = blurred | |
| let all = UIView(frame: CGRect(x: 0, y: 0, width: orig.frame.width, height: orig.frame.height * 2)) | |
| all.addSubview(o) | |
| all.addSubview(v) | |
| XCPlaygroundPage.currentPage.liveView = all |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment