大图片压缩解决方案
PS:将图片(size)最大的(width或height)压缩到指定尺寸,用一句通俗的话说就是最大边的尺寸(也就是长图还是宽图)。拿到图片之后再使用二分法将图片(data)大小压缩到指定大小
思路解析
1.计算原始和目标的对应的最大边比例。
2.判断图片的width和height哪个大,找到最大的(width或height)
如果是width大就拿原始size的宽高分别比上上一步得到的tmpW比;
如果是height就拿原始size的宽高分别比上上一步得到的tmpH比;
得到新的newSize
3.拿到新的newSize后利用UIGraphics得到新的newImg
4.在利用二分法压缩图片(data压缩)至目标大小。(注意这里的大小单位是byte。如果想要Mb需要乘上1024*1024)
/// 压缩到最大宽高 和指定大小 byte
func compressToDataWith(maxWH:CGFloat, maxSize:Int) -> UIImage{
var wh = maxWH
if maxWH <= 0{
wh = 2048
}
var newSize = self.size
let tmpH = newSize.height/wh
let tmpW = newSize.width/wh
if tmpH > 0 && tmpW > tmpH{
newSize = CGSize(width: self.size.width/tmpW, height: self.size.height/tmpW)
}else if tmpH > 1.0 && tmpW < tmpH{
newSize = CGSize(width: self.size.width/tmpH, height: self.size.height/tmpH)
}
UIGraphicsBeginImageContext(newSize)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let img = newImg?.compressImageMidToImg(maxLength: maxSize){
return img
}
return self
}
二分法压缩图片(data)
/// 二分压缩法图片 img
func compressImageMidToImg(maxLength: Int) -> UIImage {
if let data = self.compressImageMid(maxLength: maxLength), let img = UIImage(data: data){
return img
}
return self
}
/// 二分压缩法图片 data
func compressImageMid(maxLength: Int) -> Data? {
var compression: CGFloat = 1
guard var data = self.jpegData(compressionQuality: 1) else { return nil }
KWLog("压缩前kb: \( Double((data.count)/1024))")
if data.count < maxLength {
return data
}
print("压缩前kb", data.count / 1024, "KB")
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = self.jpegData(compressionQuality: compression)!
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break
}
}
if data.count < maxLength {
return data
}
return nil
}