-
-
Save natelowry/2cb32b6283495bb67a348a905b25e445 to your computer and use it in GitHub Desktop.
Convert UIImage to grayscale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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