压缩图片


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!

}

}

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