Skip to content

Instantly share code, notes, and snippets.

@asiviero
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asiviero/6b94c71b344c0e0ed2e4 to your computer and use it in GitHub Desktop.
Save asiviero/6b94c71b344c0e0ed2e4 to your computer and use it in GitHub Desktop.
A function to render a UIImage to grayscale
// Using it:
// imageview.image = imageToGrayScale(imageview.image!)
func imageToGrayScale(image: UIImage) -> UIImage {
var imageRect = CGRectMake(0,0,CGFloat(CGImageGetWidth(image.CGImage)),CGFloat(CGImageGetHeight(image.CGImage)))
var colorSpace = CGColorSpaceCreateDeviceGray()
var context = CGBitmapContextCreate(nil, CGImageGetWidth(image.CGImage), CGImageGetHeight(image.CGImage), 8, 0, colorSpace, CGBitmapInfo.ByteOrderDefault)
CGContextDrawImage(context, imageRect, image.CGImage)
var imageRef = CGBitmapContextCreateImage(context)
var newImage = UIImage(CGImage: imageRef!, scale: CGFloat(CGImageGetWidth(image.CGImage))/image.size.width, orientation: UIImageOrientation.Up)
return newImage!;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment