views:

34

answers:

1

Hi,

I have been poundering this for the last few days.. I need help to convert a color image to "black and white", not grayscale.

I what to do this with the iPhone SDK and Core Graphics, as i'm convinced this is possible.

Thanks in advanced..

+2  A: 

This is possible and I previously tried two paths:

  1. Convert to Grayscale then apply pixel by pixel conversion to B&W.
    --Problem with this is I don't get good results with images with transparency.

  2. If you're not very strict, given an RGBA image, get the pixel RGB average and convert to B&W with a supplied threshold and retain its transparency. Technically this is still RGBA but more of Black, White and Transparency.

e.g.

  UIImage *originalImage = [UIImage imageNamed:@"option_bluetooth.png"];  

  unsigned char *pixelBuffer = [GraphicsUtils getPixelData:originalImage.CGImage]; 
  size_t length = originalImage.size.width * originalImage.size.height * 4;
  CGFloat intensity;
  int bw;
  //50% threshold
  const CGFloat THRESHOLD = 0.5;
  for (int index = 0; index < length; index += 4)  
  {  
    intensity = (pixelBuffer[index] + pixelBuffer[index + 1] + pixelBuffer[index + 2]) / 3. / 255.;
    if (intensity > THRESHOLD) {
      bw = 255;
    } else {
      bw = 0;
    }
    pixelBuffer[index] = bw;


    pixelBuffer[index + 1] = bw;  
    pixelBuffer[index + 2] = bw;
  }

  CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
  CGContextRef bitmapContext=CGBitmapContextCreate(pixelBuffer, originalImage.size.width, originalImage.size.height, 8, 4*originalImage.size.width, colorSpace,  kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
  CFRelease(colorSpace);
  free(pixelBuffer);
  CGImageRef cgImage=CGBitmapContextCreateImage(bitmapContext);
  CGContextRelease(bitmapContext);

  UIImage *bwImage = [UIImage imageWithCGImage:cgImage];

I get the pixel data by writing to an offscreen context (the new way of getting the raw data which Apple suggests does not work for me)

e.g.

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

  unsigned char *rawData = malloc(imageHeight * imageWidth * 4);
  CGContextRef offscreenContext = CGBitmapContextCreate(rawData, imageWidth, imageHeight,
                                                        bitsPerComponent, bytesPerRow, colorSpace,
                                                        kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);

  CGColorSpaceRelease(colorSpace);

  CGContextDrawImage(offscreenContext, CGRectMake(0, 0, imageWidth, imageHeight), cgCropped);
  CGContextRelease(offscreenContext);
Manny
Thanks.. Will try this...
DeChinees