swift 图片压缩

2017-05-03  本文已影响422人  AirZilong

微信分享、微博分享等等,对图片大小有要求,所以需要压缩,把该方法放到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 }
        
        // 压缩大小
        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 }
        
        // 压缩大小
        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
    }

上一篇下一篇

猜你喜欢

热点阅读