我想减少像这个网站的图像大小 http://resizeimage.net 我使用下面的代码后,我的图像是1080 x 360大小120kb 但是当我使用网站时,我得到58kb 或者如果有压缩JPEG文件的库或算法
func resizeImage(_ image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let imageData = UIImageJPEGRepresentation(newImage!, 0.5)! as Data
UIGraphicsEndImageContext()
return UIImage(data:imageData)!
}
答案 0 :(得分:4)
传入UIImageJPEGRepresentation
的压缩质量决定了JPEG图像的图像质量。你有0.5,尝试低于0.1的东西:
let imageData = UIImageJPEGRepresentation(newImage!, 0.1)! as Data
来自Apple的文档:
compressionQuality
The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).