extension UIImage{
// 模糊图片
//增加模糊的效果(需要添加Accelerate.Framework)
func blurryImage(_ level:CGFloat) ->UIImage {
var tempLevel = level
//高斯模糊参数(0-1)之间,超出范围强行转成0.5
if (Float(level) <0.0||Float(level) >1.0){
tempLevel = 0.5
}
var boxSize =Int(tempLevel *100.0)
boxSize -= (boxSize % 2) +1
let imgRef =self.cgImage
var inBuffer =vImage_Buffer()
var outBuffer =vImage_Buffer()
var error =vImage_Error()
let inPRovider = imgRef?.dataProvider
let inBitmapData = inProvider!.data
inBuffer.width =vImagePixelCount((imgRef?.width)!)
inBuffer.height =vImagePixelCount((imgRef?.height)!)
inBuffer.rowBytes = (imgRef?.bytesPerRow)!
// void *
inBuffer.data =UnsafeMutableRawPointer.init(mutating:CFDataGetBytePtr(inBitmapData!))
//手动申请内存
let pixelBuffer =malloc(imgRef!.height)
outBuffer.data = pixelBuffer
outBuffer.width =vImagePixelCount((imgRef?.width)!)
outBuffer.height =vImagePixelCount((imgRef?.height)!)
outBuffer.rowBytes = (imgRef?.bytesPerRow)!
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer,nil,
0, 0,UInt32(boxSize),UInt32(boxSize),nil,
vImage_Flags(kvImageEdgeExtend))
if(kvImageNoError != error)
{
error = vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,nil,vImagePixelCount(0),vImagePixelCount(0),
UInt32(boxSize),UInt32(boxSize),nil,vImage_Flags(kvImageEdgeExtend))
}
let colorSpace =CGColorSpaceCreateDeviceRGB()
let ctx =CGContext(data: outBuffer.data,
width:Int(outBuffer.width),
height:Int(outBuffer.height),
bitsPerComponent:8,
bytesPerRow: outBuffer.rowBytes,
space: colorSpace,
bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)
let imageRef = ctx!.makeImage()
//手动释放内存
free(pixelBuffer)
returnUIImage(cgImage: imageRef!)
}
}
新闻热点
疑难解答