繁体   English   中英

使用CGColorSpaceCreateDeviceGray()将彩色的UIImage转换为灰度

[英]Convert UIImage colored to grayscale using CGColorSpaceCreateDeviceGray()

我正在尝试将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
    }

您可以改用以下功能:

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一种选择。

一种可能的替代方法可能是使用CoreImage滤镜。 请参考以下SO Post及其接受的答案 希望能帮助到你。 编码愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM