Skip to content

Instantly share code, notes, and snippets.

@natelowry
Forked from vlondon/ImageToGrayscale.swift
Last active August 2, 2021 01:22
Show Gist options
  • Save natelowry/2cb32b6283495bb67a348a905b25e445 to your computer and use it in GitHub Desktop.
Save natelowry/2cb32b6283495bb67a348a905b25e445 to your computer and use it in GitHub Desktop.
Convert UIImage to grayscale
func convertImageToGrayScale(image: UIImage) -> UIImage {
// Create image rectangle with current image width/height
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
// Grayscale color space
let colorSpace = CGColorSpaceCreateDeviceGray()
// Create bitmap content with current image size and grayscale colorspace
let context = CGContext(data: nil, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)!
// Draw image into current context, with specified rectangle using previously defined context (with grayscale colorspace)
context.draw(image.CGImage, in: imageRect)
// Create bitmap image info from pixel data in current context
let imageRef = context.makeImage()!
// Create a new UIImage object
let newImage: UIImage = UIImage(CGImage: imageRef)!
// Return the new grayscale image
return newImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment