-
-
Save waruqi/a9e222e8717f4426f4e5fd1b44de59a0 to your computer and use it in GitHub Desktop.
Fast image loading code that can be used in a background thread. Essentially forces the image to be decompressed right away, not on the fly. Uses ImageIO framework.
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
@implementation UIImage (Decompressed) | |
+ (UIImage *)decompressedImageWithContentsOfFile:(NSString *)path | |
{ | |
NSDictionary *dict = @{(id)kCGImageSourceShouldCache : @(YES)}; | |
NSData * data = [NSData dataWithContentsOfFile:path]; | |
if (data == nil) { | |
return nil; | |
} | |
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); | |
if (source == NULL) { | |
return nil; | |
} | |
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)dict); | |
CFRelease(source); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
CGContextRef context = CGBitmapContextCreate(NULL, | |
CGImageGetWidth(cgImage), | |
CGImageGetHeight(cgImage), | |
8, | |
CGImageGetWidth(cgImage) * 4, | |
colorSpace, | |
// makes system not need to do extra conversion when displayed | |
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); | |
CGColorSpaceRelease(colorSpace); | |
if (!context) { | |
CGImageRelease(cgImage); | |
return nil; | |
} | |
CGRect rect = (CGRect){CGPointZero, {CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)}}; | |
CGContextDrawImage(context, rect, cgImage); | |
CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); | |
CGContextRelease(context); | |
CGImageRelease(cgImage); | |
UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]; | |
CGImageRelease(decompressedImageRef); | |
return decompressedImage; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment