UIImage崩溃时Swift模糊扩展

时间:2016-01-25 14:12:34

标签: swift uiimage uikit

我为UIImage编写了一个扩展,并为上下文获取了nil。知道可能是什么问题吗?

def collatz(getNumber):

    if getNumber % 2 == 0:
        print(getNumber // 2)
    elif getNumber % 2 == 1:
        print(3 * getNumber + 1)

print('Please write a number')
number = collatz(int(input()))

1 个答案:

答案 0 :(得分:0)

问题是直接在CGImage上模糊而不是UIImage:

extension UIImage {
    class func blurEffect(cgImage: CGImageRef) -> UIImage! {
        return UIImage(CGImage: cgImage)
    }

    func blurEffect(boxSize: CGFloat) -> UIImage! {
        return UIImage(CGImage: bluredCGImage(boxSize))
    }

    func bluredCGImage(boxSize: CGFloat) -> CGImageRef! {
        return CGImage!.blurEffect(boxSize)
    }
}

extension CGImage {
    func blurEffect(boxSize: CGFloat) -> CGImageRef! {

        let boxSize = boxSize - (boxSize % 2) + 1

        let inProvider = CGImageGetDataProvider(self)

        let height = vImagePixelCount(CGImageGetHeight(self))
        let width = vImagePixelCount(CGImageGetWidth(self))
        let rowBytes = CGImageGetBytesPerRow(self)

        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(self) * CGImageGetHeight(self))
        var outBuffer = vImage_Buffer(data: outData, height: height, width: width, rowBytes: rowBytes)

        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(self).rawValue)
        let imageRef = CGBitmapContextCreateImage(context)

        free(outData)

        return imageRef
    }
}