title-icon-code

Adjusting the hue of an NSImage

Core Image is fantastic for complex image processing on both Mac OS X and iOS. However, it can also be used for relatively simple image adjustments with just a few lines of code.

This following method snippet adjusts the hue of an NSImage. I use it in an internal app that has colour coded icon status indicators which can’t be easily drawn totally in code. This method means that I can ship one icon resource and change it’s colour at runtime, rather than creating and shipping dozens of coloured icon resources.

As it uses Core Image, you will need to #import <QuartzCore/QuartzCore.h>.

- (NSImage*) adjustImage:(NSImage*)img withHue:(float)hue {

CIImage *inputImage = [[CIImage alloc] initWithData:[img TIFFRepresentation]];

CIFilter *hueAdjust = [CIFilter filterWithName:@"CIHueAdjust"];
[hueAdjust setValue: inputImage forKey: @"inputImage"];
[hueAdjust setValue: [NSNumber numberWithFloat: hue]
forKey: @"inputAngle"];
CIImage *outputImage = [hueAdjust valueForKey: @"outputImage"];

NSImage *resultImage = [[NSImage alloc] initWithSize:[outputImage extent].size];
NSCIImageRep *rep = [NSCIImageRep imageRepWithCIImage:outputImage];
[resultImage addRepresentation:rep];

return resultImage;

}

One Response to "Adjusting the hue of an NSImage"

Add Comment
  1. Bill

    March 2, 2014 at 4:59 pm

    Thanks for publishing this code; it’s helped me a lot.

    Reply

Submit a comment

Your email address will not be published. Required fields are marked *