Created
December 11, 2020 08:05
-
-
Save emadhegab/b9925f14b2c6c4045e44adce2f57f4c1 to your computer and use it in GitHub Desktop.
Downsampling Image for lowering memory footprint
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
func downsample(imageAt imageURL: URL, | |
to pointSize: CGSize, | |
scale: CGFloat = UIScreen.main.scale) -> UIImage? { | |
// Create an CGImageSource that represent an image | |
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary | |
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { | |
return nil | |
} | |
// Calculate the desired dimension | |
let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale | |
// Perform downsampling | |
let downsampleOptions = [ | |
kCGImageSourceCreateThumbnailFromImageAlways: true, | |
kCGImageSourceShouldCacheImmediately: true, | |
kCGImageSourceCreateThumbnailWithTransform: true, | |
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels | |
] as CFDictionary | |
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { | |
return nil | |
} | |
// Return the downsampled image as UIImage | |
return UIImage(cgImage: downsampledImage) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment