Created
October 25, 2012 08:34
-
-
Save krzysztofzablocki/3951442 to your computer and use it in GitHub Desktop.
Image decompression
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
+ (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