在将UIImage转换为压缩的JPEG表示形式并返回到UIImage之后,我试图使用下面的代码来缩小图像的大小,但是UIImage文件仍然很大,如何缩小UIImage的文件大小? / p>
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
}
答案 0 :(得分:1)
没有压缩的UIImage这样的东西。这就是UIImage的整个 point 。 UIImage是实际绘制图像的位图-您可能会认为图像的实际 pixels 。 JPEG数据只是数据,并且使用压缩。但是要将其转换为UIImage,我们必须解压缩数据并派生像素。