Created
May 22, 2021 01:36
-
-
Save christianselig/b1d7cab0772209e1e3e38993fc4bf8cf to your computer and use it in GitHub Desktop.
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
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