我想在服务器上上传图像时对其进行压缩。但是图像不应压缩到特定的高度和宽度以下。
下面是图像压缩的代码
func compressImage(image:UIImage) -> Data? {
// Reducing file size to a 10th
var actualHeight : CGFloat = image.size.height
var actualWidth : CGFloat = image.size.width
let maxHeight : CGFloat = 640.0
let maxWidth : CGFloat = 640.0
var imgRatio : CGFloat = actualWidth/actualHeight
let maxRatio : CGFloat = maxWidth/maxHeight
var compressionQuality : CGFloat = 1.0
if (actualHeight > maxHeight || actualWidth > maxWidth){
if(imgRatio < maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = maxHeight
}
else if(imgRatio > maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = maxWidth
}
else{
actualHeight = maxHeight
actualWidth = maxWidth
compressionQuality = 1
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size)
image.draw(in: rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
guard let imageData = img.jpegData(compressionQuality: compressionQuality)else{
return nil
}
return imageData
}
但是我不希望图像的宽度和高度小于250。如何避免这种情况?