Created
August 30, 2018 08:26
-
-
Save pczuchaj/a8700ed0d9b26999fa4d8407dd952e82 to your computer and use it in GitHub Desktop.
iOS App memory optimization - image downsampling technique
This file contains hidden or 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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before and after results, the same image url