swift 图片压缩

微信分享、微博分享等等,对图片大小有要求,所以需要压缩,把该方法放到Extension+UIImage即可!

// 图片压缩
    func compressImage(maxLength: Int) -> UIImage {
        let tempMaxLength: Int = maxLength / 8
        var compression: CGFloat = 1
        guard var data = UIImageJPEGRepresentation(self,compression) where data.length > tempMaxLength else { return self }
        
        // Compress by size
        var max: CGFloat = 1
        var min: CGFloat = 0
        for _ in 0..<6 {
            compression = (max + min) / 2
            data = UIImageJPEGRepresentation(self,compression)!
            if CGFloat(data.length) < CGFloat(tempMaxLength) * 0.9 {
                min = compression
            } else if data.length > tempMaxLength {
                max = compression
            } else {
                break
            }
        }
        var resultImage: UIImage = UIImage(data: data)!
        if data.length < tempMaxLength { return resultImage }
        
        // Compress by size
        var lastDataLength: Int = 0
        while data.length > tempMaxLength && data.length != lastDataLength {
            lastDataLength = data.length
            let ratio: CGFloat = CGFloat(tempMaxLength) / CGFloat(data.length)
            print("Ratio =",ratio)
            let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),height: Int(resultImage.size.height * sqrt(ratio)))
            UIGraphicsBeginImageContext(size)
            resultImage.drawInRect(CGRect(x: 0,y: 0,width: size.width,height: size.height))
            resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            data = UIImageJPEGRepresentation(resultImage,compression)!
        }
        return resultImage
    }

相关文章

Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章。自从苹果发布 Swfit 编程语言,就成为了...
快,快,快!动动您的小手,分享给更多朋友! 苹果去年推出了全新的编程语言Swift,试图让iOS开发更简单...
开发者(KaiFaX) 面向开发者、程序员的专业平台! 和今年年初承诺的一样,苹果贴出了Swift语言的源码,...
本文由@Chun发表于Chun Tips :http://chun.tips/blog/2014/12/11/shi-yong-swift-gou-jian-zi-ding-yi...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...