iPhone programming: fun with grayscale images

iPhone_programmingimgSo I was trying to do something that I thought was simple. I needed to convert an image from full color to grayscale in my iPhone application, and I easily found the CGColorSpaceCreateDeviceGray method which seemed to put me on the right track. But the complication came when I tried to use this color space with CGBitmapContextCreate. I got this error in the console:

: CGBitmapContextCreate: unsupported parameter combination:
8 integer bits/component; 16 bits/pixel; 1-component colorspace;
kCGImageAlphaPremultipliedLast; 1472 bytes/row.

So the combination of parameters was incorrect. But which one was at fault? Thankfully, I found a helpful post on the web that led me to this article:

CGBitmapContextCreate Supported Color Spaces

Very handy. Wish that this table were actually included in the documentation for the CGBitmapContextCreatemethod. Imagine how useful that would be! So, for your convenience, here is a function to create a grayscale copy of aUIImage:

UIImage *createGrayCopy(UIImage *source)
	int width = source.size.width;
	int height = source.size.height;

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

	CGContextRef context = CGBitmapContextCreate (nil,
						 8,      // bits per component


	if (context == NULL) {
		return nil;

		CGRectMake(0, 0, width, height), source.CGImage);

	UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];

	return grayImage;

Leave a Reply

Your email address will not be published. Required fields are marked *