Last active
October 22, 2021 12:15
-
-
Save vlondon/3a3c7552c83550f229dd to your computer and use it in GitHub Desktop.
Convert image 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 = CGRectMake(0, 0, image.size.width, image.size.height) | |
// Grayscale color space | |
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray() | |
// Create bitmap content with current image size and grayscale colorspace | |
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue) | |
var context = CGBitmapContextCreate(nil, UInt(image.size.width), UInt(image.size.height), 8, 0, colorSpace, bitmapInfo) | |
// Draw image into current context, with specified rectangle using previously defined context (with grayscale colorspace) | |
CGContextDrawImage(context, imageRect, image.CGImage) | |
// Create bitmap image info from pixel data in current context | |
let imageRef: CGImageRef = CGBitmapContextCreateImage(context) | |
// 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