I'm setting UImageViews within table cells using setImageWithUrl from the AFNetworking library, but I need the images to be greyscale... is there any way I can do this. I've tried a few UIImage greyscale converters, but I guess they don't work because I'm setting something that hasn't downloaded yet.
Try this method:
- (UIImage *)convertImageToGrayScale:(UIImage *)image
{
// Create image rectangle with current image width/height
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
// Grayscale color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// Create bitmap content with current image size and grayscale colorspace
CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
// Draw image into current context, with specified rectangle
// using previously defined context (with grayscale colorspace)
CGContextDrawImage(context, imageRect, [image CGImage]);
// Create bitmap image info from pixel data in current context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
// Create a new UIImage object
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
// Release colorspace, context and bitmap information
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
CFRelease(imageRef);
// Return the new grayscale image
return newImage;
}
I found it here: http://mobiledevelopertips.com/graphics/convert-an-image-uiimage-to-grayscale.html
I took the code from @Jesse Gumpo's example, above, but here it is as an interface.
@implementation UIImage ( Greyscale )
- (UIImage *)greyscaleImage
{
CIImage * beginImage = [ self CIImage ] ;
CIImage * evAdjustedCIImage = nil ;
{
CIFilter * filter = [ CIFilter filterWithName:@"CIColorControls"
keysAndValues:kCIInputImageKey, beginImage
, @"inputBrightness", @0.0
, @"inputContrast", @1.1
, @"inputSaturation", @0.0
, nil ] ;
evAdjustedCIImage = [ filter outputImage ] ;
}
CIImage * resultCIImage = nil ;
{
CIFilter * filter = [ CIFilter filterWithName:@"CIExposureAdjust"
keysAndValues:kCIInputImageKey, evAdjustedCIImage
, @"inputEV", @0.7
, nil ] ;
resultCIImage = [ filter outputImage ] ;
}
CIContext * context = [ CIContext contextWithOptions:nil ] ;
CGImageRef resultCGImage = [ context createCGImage:resultCIImage
fromRect:resultCIImage.extent ] ;
UIImage * result = [ UIImage imageWithCGImage:resultCGImage ] ;
CGImageRelease( resultCGImage ) ;
return result;
}
@end
Now you can just do this:
UIImage * downloadedImage = ... get from AFNetwork results ... ;
downloadedImage = [ downloadedImage greyscaleImage ] ;
... use 'downloadedImage' ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With