减小文件大小.png swift

时间:2016-09-17 22:01:27

标签: objective-c swift xcode uiimage png

我需要在不改变图像尺寸的情况下缩小.png扩展名图像的大小。在我创建图像时,将其保存在缓存中,文件大小为1.3 M如何将大小减小到500KB?

1 个答案:

答案 0 :(得分:0)

我认为这对你有帮助。

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)