image compression by size - iPhone SDK

后端 未结 7 1100
北海茫月
北海茫月 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:48

    I took the answer of @kgutteridge and made a similar solution for Swift 3.0 using recursive:

    extension UIImage {
        static func compress(image: UIImage, maxFileSize: Int, compression: CGFloat = 1.0, maxCompression: CGFloat = 0.4) -> Data? {
    
            if let data = UIImageJPEGRepresentation(image, compression) {
    
                let bcf = ByteCountFormatter()
                bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
                bcf.countStyle = .file
                let string = bcf.string(fromByteCount: Int64(data.count))
                print("Data size is: \(string)")
    
                if data.count > (maxFileSize * 1024 * 1024) && (compression > maxCompression) {
                    let newCompression = compression - 0.1
                    let compressedData = self.compress(image: image, maxFileSize: maxFileSize, compression: newCompression, maxCompression: maxCompression)
                    return compressedData
                }
    
                return data
            }
    
            return nil
        }
    }
    

提交回复
热议问题