iOS 图片压缩方法的示例代码

2020-01-18 20:22:41刘景俊

压缩图片尺寸

与之前类似,比较容易想到的方法是,通过循环逐渐减小图片尺寸,直到图片稍小于指定大小(maxLength)。具体代码省略。同样的问题是循环次数多,效率低,耗时长。可以用二分法来提高效率,具体代码省略。这里介绍另外一种方法,比二分法更好,压缩次数少,而且可以使图片压缩后刚好小于指定大小(不只是 < maxLength, > maxLength * 0.9)。


+ (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength {
 UIImage *resultImage = image;
 NSData *data = UIImageJPEGRepresentation(resultImage, 1);
 NSUInteger lastDataLength = 0;
 while (data.length > maxLength && data.length != lastDataLength) {
  lastDataLength = data.length;
  CGFloat ratio = (CGFloat)maxLength / data.length;
  CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
  UIGraphicsBeginImageContext(size);
  // Use image to draw (drawInRect:), image is larger but more compression time
  // Use result image to draw, image is smaller but less compression time
  [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
  resultImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  data = UIImageJPEGRepresentation(resultImage, 1);
 }
 return resultImage;
}

[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];是用新图 resultImage 绘制,也可以用原图 image 来绘制。用原图绘制,压缩后图片更接近指定大小,但是压缩次数较多,耗时较长。一张大小为 6064 KB 的图片,压缩图片尺寸,原图绘制与新图绘制结果如下

 

指定大小(KB) 原图绘制压缩后大小(KB) 原图绘制压缩次数 新图绘制压缩后大小(KB) 新图绘制压缩次数
500 498 6 498 3
300 299 4 296 3
100 99 5 98 3
50 49 6 48 3

 

两种绘制方法压缩后大小很接近,与指定大小也很接近,但原图绘制压缩次数可达到新图绘制压缩次数的两倍。建议使用新图绘制,减少压缩次数。压缩后图片明显比压缩质量模糊。