Last active
October 30, 2018 15:46
-
-
Save AmatsuZero/dba1a4b3cc3025344a73d741a03e5748 to your computer and use it in GitHub Desktop.
图片模糊化处理
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 Accelerate | |
import UIKit | |
extension UIImage { | |
private static let cache = NSCache<NSString, UIImage>() | |
func bluredImage(factor: CGFloat) -> UIImage? { | |
var blur = factor | |
if blur < 0 || blur > 1 { | |
blur = 0.5 | |
} | |
var boxSize: UInt32 = UInt32(blur * 40) | |
boxSize -= boxSize % 2 + 1 | |
guard let img = cgImage, | |
let inProvider = img.dataProvider, | |
let inBitmapData = inProvider.data, | |
let sourceData = UnsafeMutablePointer(mutating: CFDataGetBytePtr(inBitmapData)) else { | |
return nil | |
} | |
var inBuffer = vImage_Buffer(data: sourceData, | |
height: vImagePixelCount(img.width), | |
width: vImagePixelCount(img.height), | |
rowBytes: img.bytesPerRow) | |
guard let pixelBuffer = malloc(img.height * img.bytesPerRow) else { | |
return nil | |
} | |
var outBuffer = vImage_Buffer(data: pixelBuffer, | |
height: vImagePixelCount(img.width), | |
width: vImagePixelCount(img.height), | |
rowBytes: img.bytesPerRow) | |
guard vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, boxSize, boxSize, | |
nil, vImage_Flags(kvImageEdgeExtend)) == 0 else { | |
return nil | |
} | |
let colorSpace = CGColorSpaceCreateDeviceRGB() | |
guard let ctx = CGContext(data: outBuffer.data, | |
width: Int(outBuffer.width), | |
height: Int(outBuffer.height), | |
bitsPerComponent: 8, | |
bytesPerRow: outBuffer.rowBytes, | |
space: colorSpace, | |
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue), | |
let imgRef = ctx.makeImage() else { | |
return nil | |
} | |
defer { | |
pixelBuffer.deallocate() | |
sourceData.deallocate() | |
} | |
return UIImage(cgImage: imgRef) | |
} | |
func bluredImage(factor: CGFloat, forUrl: String?) -> UIImage? { | |
guard let url = forUrl, !url.isEmpty else { | |
return bluredImage(factor: factor) | |
} | |
let key = NSString(string: "\(url)#factor=\(factor)") | |
var image = UIImage.cache.object(forKey: key) | |
if image == nil, let blurImg = bluredImage(factor: factor) { | |
image = blurImg | |
UIImage.cache.setObject(blurImg, forKey: key) | |
} | |
return image | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment