Skip to content

Instantly share code, notes, and snippets.

@sendoa
Created July 4, 2013 10:06
Show Gist options
  • Save sendoa/5926504 to your computer and use it in GitHub Desktop.
Save sendoa/5926504 to your computer and use it in GitHub Desktop.
Force image decompression
// https://github.com/rs/SDWebImage
// https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F
#import "SDWebImageDecoder.h"
@implementation UIImage (ForceDecode)
+ (UIImage *)decodedImageWithImage:(UIImage *)image
{
CGImageRef imageRef = image.CGImage;
CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize};
CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
CGContextRef context = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpace, CGImageGetBitmapInfo(imageRef));
// If failed, return undecompressed image
if (!context) return image;
CGContextDrawImage(context, imageRect, imageRef);
CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(decompressedImageRef);
return decompressedImage;
}
@end
// Código adaptado de aquí: https://gist.github.com/steipete/1144242
@implementation SPOImageDecompression
+ (UIImage *)decompressImage:(UIImage *)theIimage {
CGImageRef image = theIimage.CGImage;
// make a bitmap context of a suitable size to draw to, forcing decode
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef imageContext = CGBitmapContextCreate(NULL, width, height, 8, width*4, colourSpace,
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
CGColorSpaceRelease(colourSpace);
// draw the image to the context, release it
CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
// now get an image ref from the context
CGImageRef outputImage = CGBitmapContextCreateImage(imageContext);
UIImage *cachedImage = [UIImage imageWithCGImage:outputImage];
// clean up
CGImageRelease(outputImage);
CGContextRelease(imageContext);
return cachedImage;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment