Created
January 20, 2015 06:33
-
-
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.
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
// | |
// 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)! | |
} | |
} |
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
": CGContextDrawImage: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
"