0
我需要使用.png扩展名缩小图像的大小而不更改图像的尺寸。当我创建一个图像时,将它保存在缓存中,文件大小为1.3 M如何将大小减小到500KB?缩小文件大小.png swift
我需要使用.png扩展名缩小图像的大小而不更改图像的尺寸。当我创建一个图像时,将它保存在缓存中,文件大小为1.3 M如何将大小减小到500KB?缩小文件大小.png swift
我认为这对你很有帮助。
extension UIImage {
func resizeWith(percentage: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
func resizeWith(width: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
}
和使用。
let myPicture = UIImage(data: try! Data(contentsOf: URL(string: "add the URL")!))!
let myThumb1 = myPicture.resizeWith(percentage: 0.5)
let myThumb2 = myPicture.resizeWith(width: 72.0)
谢谢@Ravi,但这改变了我需要保持相同的高度和宽度的图像尺寸。 – Carol
http://stackoverflow.com/questions/29726643/how-to-compress-of-reduce-the-size-of-an-image-before-uploading-to-parse-as-pffi/ 29726675#29726675 –
@LeoDabus谢谢!,但我需要PNG格式的图像 – Carol