Carolina
Carolina

Reputation: 457

Reduce file size .png swift

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?

Upvotes: 1

Views: 1651

Answers (1)

Ravi Dhorajiya
Ravi Dhorajiya

Reputation: 1531

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)

Upvotes: 2

Related Questions