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..<cyles {
compression = (max + min)/2
data = self.jpegData(compressionQuality: compression)!
if Double(data.count) < Double(maxLength)*0.9 {
min = compression
bestData = data
} else if data.count > maxLength {
max = compression
} else {
bestData = data
break
}
}
return bestData
}