我正在尝试将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
}
代码有什么问题吗?我需要现有代码的帮助。它以前工作。突然它不起作用。
答案 0 :(得分:3)
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
}
答案 1 :(得分:1)
您可以改用此功能:
func convertImageToDifferentColorScale(with originalImage:UIImage, imageStyle:String) -> UIImage {
let currentFilter = CIFilter(name: imageStyle)
currentFilter!.setValue(CIImage(image: originalImage), forKey: kCIInputImageKey)
let output = currentFilter!.outputImage
let context = CIContext(options: nil)
let cgimg = context.createCGImage(output!,from: output!.extent)
let processedImage = UIImage(cgImage: cgimg!)
return processedImage
}
以下是您如何使用的示例:
let newImage = convertImageToDifferentColorScale(with: UIImage(named: "0318_1")!, imageStyle: "CIPhotoEffectNoir")
testingImageView.image = newImage
在imageStyle部分,有几种不同类型的风格,如下所示:
CIColorCrossPolynomial CIColorCube CIColorCubeWithColorSpace CIColorInvert CIColorMap CIColorMonochrome CIColorPosterize CIFalseColor CIMaskToAlpha CIMaximumComponent CIMinimumComponent CIPhotoEffectChrome CIPhotoEffectFade CIPhotoEffectInstant CIPhotoEffectMono CIPhotoEffectNoir
'CIPhotoEffectNoir'
是可以为您提供gray scale
的唯一选择。
答案 2 :(得分:0)
可能的替代方案可能是使用CoreImage过滤器。请参阅以下SO Post及其Accepted Answer。希望能帮助到你。快乐的编码!