Created
October 8, 2019 17:33
-
-
Save richimf/fad8d320fbfb5059c5472e0f55ea24c2 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 | |
class ImageDownloader { | |
// DOWNLOAD IMAGE METHOD | |
func loadImage(of from: URL, completion: @escaping () -> Void ) -> UIImage { | |
let size = CGSize(width: 100, height: 140) | |
// Download and Compress image to fit container size | |
DispatchQueue.global(qos: .background).async { | |
guard let newimage = self.downloadAndCompress(url: url, newSize: size) else { return } | |
// Show in UI | |
DispatchQueue.main.async { | |
completion() | |
} | |
} | |
return UIImage() | |
} | |
// MARK: - PRIVATE METHODS | |
// DOWNLOAD AND COMPRESSING IMAGE METHOD | |
private func downloadAndCompress(url: URL, newSize: CGSize) -> UIImage? { | |
guard let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil), | |
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil), | |
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil } | |
let context = CGContext(data: nil, | |
width: Int(newSize.width), | |
height: Int(newSize.height), | |
bitsPerComponent: image.bitsPerComponent, | |
bytesPerRow: image.bytesPerRow, | |
space: image.colorSpace ?? colorSpace, | |
bitmapInfo: image.bitmapInfo.rawValue) | |
context?.interpolationQuality = .high | |
context?.draw(image, in: CGRect(origin: .zero, size: newSize)) | |
guard let scaledImage = context?.makeImage() else { return nil } | |
return UIImage(cgImage: scaledImage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment