image compression by size - iPhone SDK

后端 未结 7 1125
北海茫月
北海茫月 2020-11-30 19:56

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

7条回答
  •  感情败类
    2020-11-30 20:36

    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)!
        }
    }
    

提交回复
热议问题