Friday 4 May 2012

How to convert original Image into Black and White Image in iPhone/iPad.

How to convert original Image into Black and White Image in iPhone/iPad.


-(UIImage *)convertOriginalImageToBWImage:(UIImage *)originalImage
  {
   CGColorSpaceRef colorSapce = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, originalImage.size.width * originalImage.scale,
               originalImage.size.height * originalImage.scale, 8, originalImage.size.width * originalImage.scale,
              colorSapce, kCGImageAlphaNone);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetShouldAntialias(context, NO);
    CGContextDrawImage(context, CGRectMake(0, 0, originalImage.size.width, originalImage.size.height),
                                                [originalImage CGImage]);
   
    CGImageRef bwImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSapce);
   
    UIImage *resultImage = [UIImage imageWithCGImage:bwImage];
    CGImageRelease(bwImage);
   
    UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, originalImage.scale);
    [resultImage drawInRect:CGRectMake(0.0, 0.0, originalImage.size.width, originalImage.size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
   
  }

1 comment:

  1. Thanks bro, this code is fine but image having too much gray can we set few brightness on image

    ReplyDelete