Skip to content

Instantly share code, notes, and snippets.

View onfoot's full-sized avatar

Maciej Rutkowski onfoot

View GitHub Profile
@onfoot
onfoot / UIImage+Decompressed.swift
Last active June 20, 2018 16:52
Create a decompressed UIImage explicitly so we're able to do it on a non-UI thread. Typically UIImage loaded from a file is decompressed into an actual bitmap lazily upon use.
extension UIImage {
func decompressed() -> UIImage? {
guard let image = self.cgImage else { return nil }
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, space: colorSpace, bitmapInfo: UInt32(CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)) else { return nil }
let rect = CGRect(origin: .zero, size: CGSize(width: image.width, height: image.height))
context.draw(image, in: rect)
let decompressedImage = UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .up)
@onfoot
onfoot / UIImage+Decompressed.m
Last active September 10, 2021 09:21
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;
}