Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created May 22, 2021 01:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianselig/b1d7cab0772209e1e3e38993fc4bf8cf to your computer and use it in GitHub Desktop.
Save christianselig/b1d7cab0772209e1e3e38993fc4bf8cf to your computer and use it in GitHub Desktop.
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://external-preview.redd.it/nL7zG2Q2FkHwyJ15KgT4A7jk2R4cMddQpKb_Kx9YR8U.jpg?width=1080&crop=smart&auto=webp&s=91ee8327fdb33b3bb94cb0eab7e26221763e33f4")!
URLSession.shared.dataTask(with: url) { data, response, error in
print("Downloaded! Waiting…")
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(8)) {
// Immediately spikes approximately 7 MB upon execution
let newImage = data!.downsample()
print(newImage)
}
}.resume()
}
}
extension Data {
func downsample() -> UIImage? {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithData(self as CFData, imageSourceOptions) else { return nil }
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: 700
] 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