我想将已有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
}
但是当我将CGImageAlphaInfo
更改为None
以外的任何内容时,我的imageRef
会返回nil,从而导致应用崩溃。
有没有办法,或者我在尝试一些不可能的事情?
答案 0 :(得分:9)
使用CoreImage filters修正了它,因为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))
}
(Swift 2.0)