Skip to content

Instantly share code, notes, and snippets.

@sureshmopidevi
Last active January 27, 2021 09:50
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 sureshmopidevi/20c6b03b6c23a2e768b62a826a6a0035 to your computer and use it in GitHub Desktop.
Save sureshmopidevi/20c6b03b6c23a2e768b62a826a6a0035 to your computer and use it in GitHub Desktop.

Extension for UIImage

Compress image to desired size.

extension UIImage {
    // MARK: - UIImage+Resize
    func compressTo(_ expectedSizeInMb:Int) -> Data? {
        let sizeInBytes = expectedSizeInMb * 1024 * 1024
        var needCompress:Bool = true
        var imgData:Data?
        var compressingValue:CGFloat = 1.0
        while (needCompress && compressingValue > 0.0) {
            if let data:Data = jpegData(compressionQuality: compressingValue) {
                if data.count < sizeInBytes {
                    needCompress = false
                    imgData = data
                } else {
                    compressingValue -= 0.1
                }
            }
        }

        if let data = imgData {
            if (data.count < sizeInBytes) {
                return data
            }
        }
        return nil
    }
}

usage:

if let imageData = image.compressTo(1) {
print(imageData)
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment