Converting an image to grayscale can be thought of redrawing the image in a color space where the only colors available are only shades of gray, varying from black at the weakest intensity to white at the strongest [wikipedia]. The manual process involves converting the individual RGB values for each pixel of the image to a corresponding greyscale intensity value according to some formula. The formula described in this wikipedia article can be used for such conversion. However, for images with transparency, ie. with an alpha channel, the process is not that straightforward.
If you are programming in iOS, the SDK is going to save you some considerable effort. The process of converting a UIImage to grayscale is itself an interesting one, in addition to being very easy. Just follow the three steps described below for converting a transparent colored image to grayscale in iOS.
Step 1. Create a opaque, grayscale image from the original image
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// image is an instance of UIImage class that we will convert to grayscale CGFloat actualWidth = image.size.width; CGFloat actualHeight = image.size.height; CGRect imageRect = CGRectMake(0, 0, actualWidth, actualHeight); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); CGContextRef context = CGBitmapContextCreate(nil, actualWidth, actualHeight, 8, 0, colorSpace, kCGImageAlphaNone); CGContextDrawImage(context, imageRect, [image CGImage]); CGImageRef grayImage = CGBitmapContextCreateImage(context); CGColorSpaceRelease(colorSpace); CGContextRelease(context); |
Step 2. Create a image (mask) taking only the alpha channel from the original image
|
1 2 3 4 5 6 |
context = CGBitmapContextCreate(nil, actualWidth, actualHeight, 8, 0, nil, kCGImageAlphaOnly); CGContextDrawImage(context, imageRect, [image CGImage]); CGImageRef mask = CGBitmapContextCreateImage(context); CGContextRelease(context); |
Step 3. Create a new image from the opaque image by masking it against the image formed in Step 2
|
1 2 3 4 5 6 7 |
UIImage *grayScaleImage = [UIImage imageWithCGImage:CGImageCreateWithMask(grayImage, mask) scale:image.scale orientation:image.imageOrientation]; CGImageRelease(grayImage); CGImageRelease(mask); // greyScaleImage now holds the transparent but grayscale version of the orginal image |