在将 UIImage 转换为压缩的 JPEG 表示并返回 UIImage 后,我试图使用下面的代码缩小图像的大小,但 UIImage 文件仍然很大,如何缩小 UIImage 的文件大小?
func changeFileSize()->UIImage{
var needToCompress:Bool = true
var compressingValue:CGFloat = 1.0
let bcf = ByteCountFormatter()
while needToCompress && compressingValue > 0.0{
let data = image.jpegData(compressionQuality: compressingValue)!
if data.count < 1024 * 100{
needToCompress = false
image = UIImage(data: data)
bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
bcf.countStyle = .file
var newImage = UIImage(data: data)
let string = bcf.string(fromByteCount: Int64(newImage!.jpegData(compressionQuality: compressingValue)!.count))
print("Image Pixels: \(CGSize(width: newImage!.size.width*newImage!.scale, height: newImage!.size.height*newImage!.scale))")
print("final formatted result to be returned: \(string)")
print("New comrpession value: \(compressingValue)")
return UIImage(data: (newImage?.jpegData(compressionQuality: compressingValue))!)!
break
}
else{
compressingValue -= 0.1
bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(image.jpegData(compressionQuality: compressingValue)!.count))
print("formatted result: \(string)")
print("New comrpession value: \(compressingValue)")
}
}
bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(image.jpegData(compressionQuality: 1.0)!.count))
print("formatted result: \(string)")
compressionLabel.text = string
print("Image Pixels: \(CGSize(width: image.size.width*image.scale, height: image.size.height*image.scale))")
return image
}