Skip to content

Instantly share code, notes, and snippets.

@krzysztofzablocki
Created October 25, 2012 08:34
Show Gist options
  • Save krzysztofzablocki/3951442 to your computer and use it in GitHub Desktop.
Save krzysztofzablocki/3951442 to your computer and use it in GitHub Desktop.
Image decompression
+ (UIImage *)decompressedImageWithImage:(UIImage *)image resizeTo:(CGSize)targetSize
{
CGImageRef imageRef = image.CGImage;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
BOOL sameSize = NO;
if (CGSizeEqualToSize(targetSize, CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)))) {
targetSize = CGSizeMake(1, 1);
sameSize = YES;
}
size_t imageWidth = (size_t)targetSize.width;
size_t imageHeight = (size_t)targetSize.height;
CGContextRef context = CGBitmapContextCreate(NULL,
imageWidth,
imageHeight,
8,
// Just always return width * 4 will be enough
imageWidth * 4,
// System only supports RGB, set explicitly
colorSpace,
// Makes system don't need to do extra conversion when displayed.
alphaInfo | kCGBitmapByteOrder32Little);
CGColorSpaceRelease(colorSpace);
if (!context) {
return nil;
}
CGRect rect = (CGRect){CGPointZero, {imageWidth, imageHeight}};
CGContextDrawImage(context, rect, imageRef);
if (sameSize) {
CGContextRelease(context);
return image;
}
CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *decompressedImage = [[UIImage alloc] initWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(decompressedImageRef);
return decompressedImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment