Skip to content

Instantly share code, notes, and snippets.

@onfoot
Last active June 20, 2018 16:52
Show Gist options
  • Save onfoot/91ebb7a6cf82e26c29f12be2eb75e929 to your computer and use it in GitHub Desktop.
Save onfoot/91ebb7a6cf82e26c29f12be2eb75e929 to your computer and use it in GitHub Desktop.
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)
return decompressedImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment