UIImageJPEGRepresentation是降低图像质量的绝佳功能。
我只是想将图像降级为 1MB 。
是的,有一种循环方式,我们可以应用多次检查,直到我们收到1024KB的数据计数。
let image = UIImage(named: "test")!
if let imageData = UIImagePNGRepresentation(image) {
let kb = imageData.count / 1024
if kb > 1024 {
let compressedData = UIImageJPEGRepresentation(image, 0.2)!
}
}
有什么优雅的解决方案吗?
答案 0 :(得分:1)
您可以创建一个功能
func resize(image:UIImage) -> Data? {
if let imageData = UIImagePNGRepresentation(image){ //if there is an image start the checks and possible compression
let size = imageData.count / 1024
if size > 1024 { //if the image data size is > 1024
let compressionValue = CGFloat(1024 / size) //get the compression value needed in order to bring the image down to 1024
return UIImageJPEGRepresentation(image, compressionValue) //return the compressed image data
}
else{ //if your image <= 1024 nothing needs to be done and return it as is
return imageData
}
}
else{ //if it cant get image data return nothing
return nil
}
}