swift 二分法压缩图片 2022-07-21

    /// - maxLength: 指定data最大的体积
    func compressImageMid(maxLength: Int,image:UIImage?) -> Data? {
        var compression: CGFloat = 1
             let minCompression: CGFloat = 0.1
             var imageData = image?.jpegData(compressionQuality: compression)
             if imageData?.count ?? 0 < maxLength {
                 return imageData
             }
             while imageData?.count ?? 0 > maxLength, compression > minCompression {
                 compression -= 0.1
                 imageData = image?.jpegData(compressionQuality: compression)
             }
             if imageData?.count ?? 0 > maxLength {
                 return nil
             }
             return imageData
        }

你可能感兴趣的:(swift 二分法压缩图片 2022-07-21)