2016-09-17 112 views
0

我需要使用.png擴展名縮小圖像的大小而不更改圖像的尺寸。當我創建一個圖像時,將它保存在緩存中,文件大小爲1.3 M如何將大小減小到500KB?縮小文件大小.png swift

+0

http://stackoverflow.com/questions/29726643/how-to-compress-of-reduce-the-size-of-an-image-before-uploading-to-parse-as-pffi/ 29726675#29726675 –

+0

@LeoDabus謝謝!,但我需要PNG格式的圖像 – Carol

回答

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) 
+1

謝謝@Ravi,但這改變了我需要保持相同的高度和寬度的圖像尺寸。 – Carol