Skip to content

Instantly share code, notes, and snippets.

@PMUNOZ08
Last active December 13, 2015 19:09
Show Gist options
  • Select an option

  • Save PMUNOZ08/4960985 to your computer and use it in GitHub Desktop.

Select an option

Save PMUNOZ08/4960985 to your computer and use it in GitHub Desktop.
Given an UIImage return a new UIImage with the colors in gray scale
- (UIImage *)convertToGrayscale:(UIImage*)img {
CGImageRef imageRef = [img CGImage];
int widthI = CGImageGetWidth(imageRef);
int heightI = CGImageGetHeight(imageRef);
// the pixels will be painted to this array
uint32_t *pixels = (uint32_t *) malloc(widthI * heightI * sizeof(uint32_t));
// clear the pixels so any transparency is preserved
memset(pixels, 0, width * height * sizeof(uint32_t));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// create a context with RGBA pixels
CGContextRef context = CGBitmapContextCreate(pixels, widthI, heightI, 8, widthI * sizeof(uint32_t), colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
// paint the bitmap to our context which will fill in the pixels array
CGContextDrawImage(context, CGRectMake(0, 0, widthI, heightI), [img CGImage]);
for(int y = 0; y < heightI; y++) {
for(int x = 0; x < widthI; x++) {
uint8_t *rgbaPixel = (uint8_t *) &pixels[y * widthI + x];
// convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
// set the pixels to gray
rgbaPixel[RED] = gray;
rgbaPixel[GREEN] = gray;
rgbaPixel[BLUE] = gray;
}
}
// create a new CGImageRef from our context with the modified pixels
CGImageRef image = CGBitmapContextCreateImage(context);
// we're done with the context, color space, and pixels
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(pixels);
// make a new UIImage to return
UIImage *resultUIImage = [UIImage imageWithCGImage:image scale:1.0 orientation:img.imageOrientation];
// we're done with image now too
CGImageRelease(image);
return resultUIImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment