将图像转换为黑白,同时保留alpha通道

Gal*_*lip 0 image-processing ios swift

我想将已经具有Alpha通道(RGBA)的png图像转换为黑白图像.

我使用以下类别来做:

func convertToGrayScale() -> UIImage {
    let imageRect:CGRect = CGRectMake(0, 0, self.size.width, self.size.height)
    let colorSpace = CGColorSpaceCreateDeviceGray()
    let width = self.size.width
    let height = self.size.height

    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.None.rawValue)
    let context = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue)

    CGContextDrawImage(context, imageRect, self.CGImage)
    let imageRef = CGBitmapContextCreateImage(context)
    let newImage = UIImage(CGImage: imageRef!)

    return newImage
}
Run Code Online (Sandbox Code Playgroud)

但是当我改变CGImageAlphaInfo其他任何东西时None,我的imageRef回报为零,因此导致应用崩溃.

有没有办法,或者我在尝试一些不可能的事情?

Gal*_*lip 9

修正了它使用CoreImage过滤器,如Yi.Zhang建议:)

func convertToGrayScale() -> UIImage {
    let filter: CIFilter = CIFilter(name: "CIPhotoEffectMono")!
    filter.setDefaults()
    filter.setValue(CoreImage.CIImage(image: self)!, forKey: kCIInputImageKey)

    return UIImage(CGImage: CIContext(options:nil).createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
}
Run Code Online (Sandbox Code Playgroud)

(Swift 2.0)