Skip to content

Instantly share code, notes, and snippets.

@emadhegab
Created December 11, 2020 08:05
Show Gist options
  • Save emadhegab/b9925f14b2c6c4045e44adce2f57f4c1 to your computer and use it in GitHub Desktop.
Save emadhegab/b9925f14b2c6c4045e44adce2f57f4c1 to your computer and use it in GitHub Desktop.
Downsampling Image for lowering memory footprint
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