Skip to content

Instantly share code, notes, and snippets.

@waruqi
Forked from onfoot/UIImage+Decompressed.m
Created September 10, 2021 09:21
Show Gist options
  • Save waruqi/a9e222e8717f4426f4e5fd1b44de59a0 to your computer and use it in GitHub Desktop.
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.
@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