Created
August 7, 2011 21:49
-
-
Save mikeabdullah/1130831 to your computer and use it in GitHub Desktop.
Scaling images for the web, maintaining colorspace when reasonable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (CGImageRef)renderImage:(CIImage *)scaledImage fromSource:(CIImage *)sourceImage; | |
{ | |
// We want sRGB as fallback output colorspace | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); | |
CIContext *context = [CIContext contextWithCGContext:nil | |
options:[NSDictionary dictionaryWithObjectsAndKeys: | |
colorSpace, kCIContextOutputColorSpace, | |
nil]]; | |
CFRelease(colorSpace); colorSpace = NULL; | |
// Only 10.6+ is willing to divulge image colorspace | |
if ([image respondsToSelector:@selector(colorSpace)]) | |
{ | |
colorSpace = [image colorSpace]; | |
} | |
CGImageRef result = NULL; | |
if (colorSpace) | |
{ | |
// Web browsers only support RGB and monochrome color spaces | |
CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); | |
if (model == kCGColorSpaceModelRGB || model == kCGColorSpaceModelMonochrome) | |
{ | |
result = [[self sharedContext] createCGImage:scaledImage | |
fromRect:[scaledImage extent] | |
format:kCIFormatARGB8 | |
colorSpace:colorSpace]; | |
} | |
} | |
if (!result) | |
{ | |
result = [coreImageContext createCGImage:scaledImage fromRect:[scaledImage extent]]; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment