如何在 Swift 中将 png 图像的文件大小减小到小于 64KB 且不丢失透明背景并保持 512 X 512 像素。
我试过这段代码:
func resizeImageOriginalSize(targetSize: CGSize) -> UIImage {
var actualHeight: Float = Float(self.size.height)
var actualWidth: Float = Float(self.size.width)
let maxHeight: Float = Float(targetSize.height)
let maxWidth: Float = Float(targetSize.width)
var imgRatio: Float = actualWidth / actualHeight
let maxRatio: Float = maxWidth / maxHeight
var compressionQuality: Float = 0.5
//50 percent compression
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 = 0.4
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
UIGraphicsBeginImageContextWithOptions(rect.size, false, CGFloat(compressionQuality))
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
但尺寸不是我所期望的。