Skip to content

Instantly share code, notes, and snippets.

@pczuchaj
Created August 30, 2018 08:26
Show Gist options
  • Save pczuchaj/a8700ed0d9b26999fa4d8407dd952e82 to your computer and use it in GitHub Desktop.
Save pczuchaj/a8700ed0d9b26999fa4d8407dd952e82 to your computer and use it in GitHub Desktop.
iOS App memory optimization - image downsampling technique
// Image downsampling technique provides smaller image buffer allocations which leads to memory optimization
extension UIImageView {
func downsampleImage(from imageUrl: URL) -> UIImage {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageUrl as CFURL, imageSourceOptions) else { return UIImage() }
let maxDimensionInPixels = max(self.bounds.size.width, self.bounds.size.height) * self.traitCollection.displayScale
let downsampleOptions =
[kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
guard let downsampledImage =
CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return UIImage() }
return UIImage(cgImage: downsampledImage)
}
}
//example usage
imageView.image = imageView.downsampleImage(from: imgUrl)
@pczuchaj
Copy link
Author

pczuchaj commented Aug 30, 2018

Before and after results, the same image url

before after

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment