Skip to content

Instantly share code, notes, and snippets.

@ntnmrndn
Created January 20, 2015 06:33
Show Gist options
  • Save ntnmrndn/045abc4875291a50018b to your computer and use it in GitHub Desktop.
Save ntnmrndn/045abc4875291a50018b to your computer and use it in GitHub Desktop.
A swift UIImage category to convert an image to black and white (truly, in shades of gray); preserving alpha as alpha.
//
// UIImage+convertToGreyScale.swift
// itooch
//
// Created by Antoine Marandon on 15/01/2015.
// Copyright (c) 2015 eduPad. All rights reserved.
//
import Foundation
extension UIImage {
private func convertToGrayScaleNoAlpha() -> CGImageRef {
let colorSpace = CGColorSpaceCreateDeviceGray();
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue)
let context = CGBitmapContextCreate(nil, UInt(size.width), UInt(size.height), 8, 0, colorSpace, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage)
return CGBitmapContextCreateImage(context)
}
/**
Return a new image in shades of gray + alpha
*/
func convertToGrayScale() -> UIImage {
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.Only.rawValue)
let context = CGBitmapContextCreate(nil, UInt(size.width), UInt(size.height), 8, 0, nil, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);
let mask = CGBitmapContextCreateImage(context)
return UIImage(CGImage: CGImageCreateWithMask(convertToGrayScaleNoAlpha(), mask), scale: scale, orientation:imageOrientation)!
}
}
@dhoerl
Copy link

dhoerl commented Mar 4, 2017

Note that iOS/macOS do not support gray scale with alpha (you have to use a RGB image with all 3 set to the same value + alpha to get this affect). In Swift 3 the function (not extension) to get gray scale is:

private func convertToGrayScale(image: CGImage) -> CGImage {
	let height = image.height
	let width = image.width
	let colorSpace = CGColorSpaceCreateDeviceGray();
	let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
	let context = CGContext.init(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
	let rect = CGRect(x: 0, y: 0, width: width, height: height)
	context.draw(image, in: rect)
	return context.makeImage()!
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment