图片压缩到制定大小

swift 4.2

将图片压缩到制定的大小,使用二分法进行循环,让计算值接近目标值

func compressQuality(_ maxLength:NSInteger,_ cyles:Int = 6) -> Data {
        var compression:CGFloat = 1
        var data = self.jpegData(compressionQuality: compression)!
        if data.count < maxLength {
            return data
        }
        var max:CGFloat = 1
        var min:CGFloat = 0
        var bestData:Data = data
        for _ in 0.. maxLength {
                max = compression
            } else {
                bestData = data
                break
            }
        }
        return bestData
    }

 

你可能感兴趣的:(Swift)