iPhone programming: fun with grayscale images.

So 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:

<Error>: 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 CGBitmapContextCreate method. Imagine how useful that would be! So, for your convenience, here is a function to create a grayscale copy of a UIImage:

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

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

	CGContextRef context = CGBitmapContextCreate (nil,
						 width,
						 height,
						 8,      // bits per component
						 0,
						 colorSpace,
						 kCGImageAlphaNone);

	CGColorSpaceRelease(colorSpace);

	if (context == NULL) {
		return nil;
	}

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

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

	return grayImage;
}

About smeans
I'm trying to be a Renaissance man in an age of specialization. I'm a father, a writer, a programmer, a lover, and a fighter. I'm trying real hard to be the shepard, but sometimes I'm afraid that I am the tyranny of evil men.

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.