当前位置: 代码迷 >> 综合 >> swift压缩图片的方法
  详细解决方案

swift压缩图片的方法

热度:72   发布时间:2023-11-02 07:50:57.0

       在项目中往往很多时候需要实现上传图片,但在对多张图片进行上传时往往会出现内存警告的问题,(当第二次警告时候app就会闪退)这是由于ios默认只给20M的内存。所以要解决这个问题就需要对图片进行压缩上传,下面是我封装的一个压缩图片的方法:

static func zipImage(currentImage: UIImage,scaleSize:CGFloat,percent: CGFloat) -> NSData{//压缩图片尺寸UIGraphicsBeginImageContext(CGSizeMake(currentImage.size.width*scaleSize, currentImage.size.height*scaleSize))currentImage.drawInRect(CGRect(x: 0, y: 0, width: currentImage.size.width*scaleSize, height:currentImage.size.height*scaleSize))let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()//高保真压缩图片质量//UIImageJPEGRepresentation此方法可将图片压缩,但是图片质量基本不变,第二个参数即图片质量参数。let imageData: NSData = UIImageJPEGRepresentation(newImage, percent)!return imageData}