swift图片压缩到制定大小

释放双眼,带上耳机,听听看~!

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
}

人已赞赏
iOS文章

iOS_报错"Collection NSArrayM was mutated while being enumerated"

2020-2-15 10:55:33

iOS文章

iOS Charts 3.0框架绘制-柱形图表

2020-2-15 11:31:44

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索