swift图片压缩

二话不说,上代码

 extension UIImage{
  func xc_resizeImage() -> UIImage{
    let width:CGFloat = self.size.width
    let height:CGFloat = self.size.height
    let scale:CGFloat = width/height
    var sizeChange:CGSize = CGSize()
    if width <= 1280 && height <= 1280{
    //图片宽或者高均小于或等于1280时图片尺寸保持不变,不改变图片大小
        return self
    }else if width > 1280 || height > 1280 {
        if scale <= 2 && scale >= 1 {
            //比例为1和2之间,宽比高长
            let changedWidth:CGFloat = 1280
            let changedheight:CGFloat = changedWidth / scale
            sizeChange = CGSize(width: changedWidth, height: changedheight)
        }else if scale >= 0.5 && scale <= 1 {
             //比例为0.5和1之间,高比宽长
            let changedheight:CGFloat = 1280
            let changedWidth:CGFloat = changedheight * scale
            sizeChange = CGSize(width: changedWidth, height: changedheight)
        }else if width > 1280 && height > 1280 {
            //宽高都大于1280
            if scale > 2 {
                //高的值比较小
                let changedheight:CGFloat = 1280
                let changedWidth:CGFloat = changedheight * scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
            }else if scale < 0.5{
                //宽的值比较小
                let changedWidth:CGFloat = 1280
                let changedheight:CGFloat = changedWidth / scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
            }
        }else {
            //d, 宽或者高,只有一个大于1280,并且宽高比超过2
            if self.size.width>self.size.height{
                //宽比高长,选择高压缩,640可以自己调整(超长图的宽高尽量小点,避免尺寸太大,比如说12400*1280)
                if self.size.height>640{
                    let changedheight:CGFloat = 640
                    let changedWidth:CGFloat = changedheight * scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                }else{
                    return self
                }
            }else{
                //高比宽长,选择宽压缩
                if self.size.width>640{
                    let changedWidth:CGFloat = 640
                    let changedheight:CGFloat = changedWidth / scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                }else{
                    return self
                }
            }
        }
    }
    //下面流程化操作
    UIGraphicsBeginImageContext(sizeChange)
    self.draw(in: CGRect(x: 0, y: 0, width: sizeChange.width, height: sizeChange.height))
    guard let resizedImg = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
    UIGraphicsEndImageContext()
    return resizedImg
  }
}

具体用法

let tempImage:UIImage = image.xc_resizeImage()
if let imgData:Data = tempImage.jpegData(compressionQuality: 1) {
   //上传图片等操作
}

你可能感兴趣的:(swift图片压缩)