我目前正在使用以下代码从UIImage对象生成固定大小的JPEG图像:
var ratio: CGFloat = 1
var imageData : Data = UIImageJPEGRepresentation(edited, ratio)!
while imageData.count > 200000 {
if ratio == 0.1 {
break
}
ratio = ratio - 0.1
imageData = UIImageJPEGRepresentation(edited, ratio)!
}
然而,这段代码似乎效率不高,因为我需要不断降低比率,直到图像大小低于指定值(200 kb)。有没有更好的方法在swift中实现这种行为?
答案 0 :(得分:1)
使用此扩展名来缩小图像大小。
extension UIImage {
func resizeImage(factor: CGFloat) -> UIImage? {
let newWidth = self.size.width * factor // Calculate size from factor.
let newHeight = self.size.height * factor
let size = CGSize(width: newWidth, height: newHeight)
return resizeImage(targetSize: size) // Return image with scaled factor.
}
func resizeImage(targetSize: CGSize) -> UIImage? {
let originalSize = self.size
let widthRatio = targetSize.width / originalSize.width
let heightRatio = targetSize.height / originalSize.height
let ratio = min(widthRatio, heightRatio)
let newSize = CGSize(width: originalSize.width * ratio, height: originalSize.height * ratio)
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
使用此功能,我们可以使用上面的代码来实现您的目标。
var imageData: Data = UIImageJPEGRepresentation(edited, 1.0)
while imageData.count < 200000 {
imageData = UIImageJPEGRepresentation(UIImage(data: imageData)!.resizeImage(factor: 0.9)!, 1.0)
// imageData will be incremented down each time by a factor of 0.1 (1.0 - ratio)
}
编辑:如果您不想加入扩展程序,则只需使用imageData = UIImageJPEGRepresentation(imageData, 0.9)
,因为它每次仍会按比例缩小0.1倍。
答案 1 :(得分:0)
你几乎完成了它,你可以让extension
调整Image By K-Byte的大小
extension UIImage {
func resizeImageByKByte(kb: Int) {
let maxByte : Int64 = Int64(kb * 1024)
var maxCompressQuality: CGFloat = 1
var imageByte : Int64 = Int64(UIImageJPEGRepresentation(self, 1)?.count ?? 0)
while imageByte > maxByte {
imageByte = Int64(UIImageJPEGRepresentation(self, maxCompressQuality)?.count ?? 0)
maxCompressQuality -= 0.1
}
}
}
像这样使用:
UIImage().resizeImageByKByte(kb: 200) // 200 KB