I need to reduce the size of an image with .png extension without changing the dimensions of the image. At the time I create an image, keep it in the cache and the file size is 1.3 M How can i reduce the size to 500KB?
Asked
Active
Viewed 1,553 times
1
-
http://stackoverflow.com/questions/29726643/how-to-compress-of-reduce-the-size-of-an-image-before-uploading-to-parse-as-pffi/29726675#29726675 – Leo Dabus Sep 17 '16 at 22:31
-
@LeoDabus thanks!, but I need the image in png format – Carolina Sep 17 '16 at 22:42
1 Answers
2
I think it's helpful for you.
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
}
}
and use.
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 Dhorajiya
- 1,531
- 3
- 21
- 26
-
3Thanks @Ravi, but this change the image dimension i need to keep the same height and width. – Carolina Sep 18 '16 at 17:35