美文网首页
压缩图片

压缩图片

作者: 不知名开发者 | 来源:发表于2018-09-13 12:18 被阅读0次
    
    extensionUIImage{
    
    funccompressImage(image:UIImage) ->UIImage{
    
    varresImage = image
    
    if(image.size.width>=400){
    
    letsize =CGSize.init(width: (image.size.width) /5, height: (image.size.height) /5)
    
    resImage =self.resizesImage(image: image, newSize: size)
    
    }
    
    varcompress:CGFloat=0.9
    
    vardata:NSData=UIImageJPEGRepresentation(resImage, compress)!asNSData
    
    whiledata.length>10240&&compress >0.01{
    
    compress -=0.02
    
    data =UIImageJPEGRepresentation(resImage, compress)!asNSData
    
    }
    
    returnUIImage(data: dataasData)!
    
    }
    
    funcresizesImage(image:UIImage, newSize:CGSize) ->UIImage{
    
    UIGraphicsBeginImageContextWithOptions(newSize,false,UIScreen.main.scale)
    
    image.draw(in:CGRect(x:0, y:0, width: newSize.width, height: newSize.height))
    
    letnewImage =UIGraphicsGetImageFromCurrentImageContext()
    
    UIGraphicsEndImageContext()
    
    returnnewImage!
    
    }
    
    }
    
    

    相关文章

      网友评论

          本文标题:压缩图片

          本文链接:https://www.haomeiwen.com/subject/pnrwgftx.html