Last active
January 26, 2021 14:27
-
-
Save Gagan5278/8f2e370d8883cbd8f4e062bd0dbcd8e9 to your computer and use it in GitHub Desktop.
Reducing image size with Downsampling [Using ImageIO]
This file contains 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) | |
} | |
//DESCRIPTION: | |
imageURL: The image URL. It can be a web URL or a local image path. | |
pointSize: The desired size of the downsampled image. Usually, this will be the UIImageView's frame size. | |
scale: The downsampling scale factor. Usually, this will be the scale factor associated with the screen (we usually refer to it as @2x or @3x). That's why you can see that its default value has been set to UIScreen.main.scale. | |
//HOW TO USE: | |
let filePath = Bundle.main.url(forResource: "image_name", withExtension: "jpg")! | |
let downsampledImage = downsample(imageAt: filePath, to: yourImageView.bounds.size) | |
yourImageView.image = downsampledImage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment