Search code examples
iosswiftimagegrayscale

Convert UIImage colored to grayscale using CGColorSpaceCreateDeviceGray()


I am trying to convert a UIImage to GrayScale. All it make is totally a black image.

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
}

Is there anything wrong with the code? I need help with existing code. It was working previously. Suddenly its not working.


Solution

  • 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
        }