Created
August 2, 2024 10:57
-
-
Save Shubham-0812/4588223d3ca504e8ed2d7ca6109627db to your computer and use it in GitHub Desktop.
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
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