Skip to content

Instantly share code, notes, and snippets.

@mikeabdullah
Created August 7, 2011 21:49
Show Gist options
  • Save mikeabdullah/1130831 to your computer and use it in GitHub Desktop.
Save mikeabdullah/1130831 to your computer and use it in GitHub Desktop.
Scaling images for the web, maintaining colorspace when reasonable
- (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