我正在尝试将UIImage转换为GrayScale。它所产生的完全是黑色图像。
func convertToGrayScale2(image: UIImage) -> UIImage {
let imageRect:CGRect = CGRect(x:0, y:0, width:image.size.width, height: image.size.height)
let colorSpace = CGColorSpaceCreateDeviceGray()
let width = image.size.width
let height = image.size.height
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
let imageRef = context!.makeImage()
context?.draw(imageRef!, in: imageRect)
let newImage = UIImage(cgImage: imageRef!)
return newImage
}
代码有什么问题吗?我需要有关现有代码的帮助。它以前在工作。突然无法正常工作。
最佳答案
func convertToGrayScale(image: UIImage) -> UIImage {
let imageRect:CGRect = CGRect(x:0, y:0, width:image.size.width, height: image.size.height)
let colorSpace = CGColorSpaceCreateDeviceGray()
let width = image.size.width
let height = image.size.height
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
//have to draw before create image
context?.draw(image.cgImage!, in: imageRect)
let imageRef = context!.makeImage()
let newImage = UIImage(cgImage: imageRef!)
return newImage
}
关于ios - 使用CGColorSpaceCreateDeviceGray()将彩色的UIImage转换为灰度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43040333/