I would like to compress images (camera/photo library) and then send it to the server. I know I can compress by height and width, but I would like to compress the images by
Swift 4:
extension UIImage {
func compressTo(bytes: Int) -> UIImage {
var compression: CGFloat = 0.9
let maxCompression: CGFloat = 0.1
let maxSize: Int = bytes * 1024
var imageData = jpegData(compressionQuality: compression)!
while imageData.count > maxSize && compression > maxCompression {
compression -= 0.1
imageData = jpegData(compressionQuality: compression)!
}
return UIImage(data: imageData)!
}
}