Skip to content

Instantly share code, notes, and snippets.

@k06a
Last active November 25, 2015 14:18
Show Gist options
  • Save k06a/ed93266b91e382127c97 to your computer and use it in GitHub Desktop.
Save k06a/ed93266b91e382127c97 to your computer and use it in GitHub Desktop.
UIImage+Grayscale
@implementation UIImage (Grayscale)
UIImage *grayscaleImageFromCIImage(CIImage *image, CGFloat scale) {
CIImage *blackAndWhite = [CIFilter filterWithName:@"CIColorControls" keysAndValues:kCIInputImageKey, image, @"inputBrightness", @0.0, @"inputContrast", @1.1, @"inputSaturation", @0.0, nil].outputImage;
CIImage *output = [CIFilter filterWithName:@"CIExposureAdjust" keysAndValues:kCIInputImageKey, blackAndWhite, @"inputEV", @0.7, nil].outputImage;
CGImageRef ref = [[CIContext contextWithOptions:nil] createCGImage:output fromRect:output.extent];
UIImage *result = [UIImage imageWithCGImage:ref scale:scale orientation:UIImageOrientationUp];
CGImageRelease(ref);
return result;
}
UIImage *grayscaleImageFromCGImage(CGImageRef imageRef, CGFloat scale) {
NSInteger width = CGImageGetWidth(imageRef) * scale;
NSInteger height = CGImageGetHeight(imageRef) * scale;
NSMutableData *pixels = [NSMutableData dataWithLength:width*height];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, width, height, 8, width, colorSpace, 0);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(context);
UIImage *result = [UIImage imageWithCGImage:ref scale:scale orientation:UIImageOrientationUp];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(ref);
return result;
}
- (UIImage *)grayscaleImage {
if (self.CIImage)
return grayscaleImageFromCIImage(self.CIImage, self.scale);
if (self.CGImage)
return grayscaleImageFromCGImage(self.CGImage, self.scale);
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment