我的图片上传限制为2 MB。因此,如果用户尝试上传大于2 MB的图像,我希望在不降低分辨率的情况下减小其大小。
我如何实现这一目标?我试过这样的东西,但它不起作用:
var fileSize = UIImageJPEGRepresentation(image, 1)!.length
print("before File size:")
print(fileSize)
while fileSize > MyConstants.MAX_ATTACHMENT_SIZE{
let mydata = UIImageJPEGRepresentation(image, 0.75)
fileSize = mydata!.length
image = UIImage(data: mydata!)!
print("make smaller \(fileSize)")
}
print("after File size:")
print(UIImageJPEGRepresentation(image, 1)!.length)
输出:
before File size:
2298429
make smaller 846683
after File size:
2737491
答案 0 :(得分:-1)
let mydata = UIImageJPEGRepresentation(image, 0.75)
fileSize = mydata!.length
image = UIImage(data: mydata!)!
这是正确的方法。您可以根据0.1 to 1
设置不同的比例,以减少图像的质量和尺寸。
print(UIImageJPEGRepresentation(image, 1)!.length)
此行再次将图片的质量和尺寸或分辨率提高到最大(because scale = 1)
答案 1 :(得分:-1)
正如@Lion所说,你必须要有质量才能达到令人满意的文件大小。不过我注意到了:
print(UIImageJPEGRepresentation(image, 1)!.length)
将以最高质量打印图像长度。这是误导性的,因为在while条件下,您实现的文件较小。
while fileSize > MyConstants.MAX_ATTACHMENT_SIZE{
let mydata = UIImageJPEGRepresentation(image, 0.75)
fileSize = mydata!.length
image = UIImage(data: mydata!)!
print("make smaller \(fileSize)")
}