Skip to content

Instantly share code, notes, and snippets.

@Shubham-0812
Created August 2, 2024 10:57
Show Gist options
  • Save Shubham-0812/4588223d3ca504e8ed2d7ca6109627db to your computer and use it in GitHub Desktop.
Save Shubham-0812/4588223d3ca504e8ed2d7ca6109627db to your computer and use it in GitHub Desktop.
import UIKit
struct Downsampler {
// MARK: - functions
static func downsampleImage(imageURL: URL, frameSize: CGSize,
scale: CGFloat = UIScreen.main.scale) -> UIImage? {
/// creates an CGImageSource that represent an image
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else {
return nil
}
/// downsample the image
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: max(frameSize.width, frameSize.height) * scale
] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0,
downsampleOptions) else {
return nil
}
return UIImage(cgImage: downsampledImage)
}
static func downsampleImage(imageData: Data, frameSize: CGSize,
scale: CGFloat = UIScreen.main.scale) -> UIImage? {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, imageSourceOptions) else { return nil }
/// downsample the image
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: max(frameSize.width, frameSize.height) * scale
] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0,
downsampleOptions) else {
return nil
}
return UIImage(cgImage: downsampledImage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment