iOS 图片压缩
压缩图片有两种方式
(1)压缩图片尺寸(Size) (2)压缩图片质量(Quality)
1、第一种是压缩图片的尺寸,如下:
/**
压缩图片到指定尺寸大小
@param image 原始图片
@param size 目标大小
@return 生成图片
*/
- (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size {
if (!image) {
return image;
}
UIImage * resultImage = image;
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIGraphicsEndImageContext();
return image;
}
2、第二种是压缩图片质量
2.1 循环遍历压缩,如下:
/**
压缩图片到指定文件大小
@param image 目标图片
@param size 目标大小(最大值)
@return 返回的图片文件
*/
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size {
if (!image) {
return image;
}
if (size < 1) {
return image;
}
NSData * data = UIImageJPEGRepresentation(image, 1.0);
CGFloat dataKBytes = data.length/1024.0;
if (data.length < maxLength) return data;
CGFloat maxQuality = 0.9f;
CGFloat lastData = dataKBytes;
while (dataKBytes > size && maxQuality > 0.01f) {
maxQuality = maxQuality - 0.01f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length / 1024.0;
if (lastData == dataKBytes) break;
else
lastData = dataKBytes;
}
return data;
}
2.2 二分法质量压缩
# 2.2.1 #
+ (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
return resultImage;
}
# 2.2.2 #
static func compressImageQuality(_ image: UIImage, toByte maxLength: Int) -> UIImage {
var compression: CGFloat = 1
guard var data = UIImageJPEGRepresentation(image, compression),
data.count > maxLength else { return image }
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = UIImageJPEGRepresentation(image, compression)!
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break
}
}
return UIImage(data: data)!
}
注: 当图片大小小于 maxLength,大于 maxLength * 0.9 时,不再继续压缩。最多压缩 6 次,1/(2^6) = 0.015625 < 0.02,也能达到每次循环 compression 减小 0.02 的效果。这样的压缩次数比循环减小 compression 少,耗时短。需要注意的是,当图片质量低于一定程度时,继续压缩没有效果。也就是说,compression 继续减小,data 也不再继续减小。压缩图片质量的优点在于,尽可能保留图片清晰度,图片不会明显模糊;缺点在于,不能保证图片压缩后小于指定大小。
2.3 二分法压缩通过压缩图片尺寸,将图片压缩至指定大小
与之前类似,比较容易想到的方法是,通过循环逐渐减小图片尺寸,直到图片稍小于指定大小(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;
}
static func compressImageSize(_ image: UIImage, toByte maxLength: Int) -> UIImage {
guard var data = UIImageJPEGRepresentation(image, 1) else { return image }
var resultImage: UIImage = image
var lastDataLength: Int = 0
while data.count > maxLength, data.count != lastDataLength {
lastDataLength = data.count
let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
height: Int(resultImage.size.height * sqrt(ratio)))
UIGraphicsBeginImageContext(size)
resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: 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 |
两种绘制方法压缩后大小很接近,与指定大小也很接近,但原图绘制压缩次数可达到新图绘制压缩次数的两倍。建议使用新图绘制,减少压缩次数。压缩后图片明显比压缩质量模糊。
需要注意的是绘制尺寸的代码 CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
,每次绘制的尺寸 size,要把宽 width 和 高 height 转换为整数,防止绘制出的图片有白边。
压缩图片尺寸可以使图片小于指定大小,但会使图片明显模糊(比压缩图片质量模糊)。
2.4 两种图片压缩方法结合
如果要保证图片清晰度,建议选择压缩图片质量。如果要使图片一定小于指定大小,压缩图片尺寸可以满足。对于后一种需求,还可以先压缩图片质量,如果已经小于指定大小,就可得到清晰的图片,否则再压缩图片尺寸。
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return resultImage;
// Compress by size
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);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}
static func compressImage(_ image: UIImage, toByte maxLength: Int) -> UIImage {
var compression: CGFloat = 1
guard var data = UIImageJPEGRepresentation(image, compression),
data.count > maxLength else { return image }
// Compress by size
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = UIImageJPEGRepresentation(image, compression)!
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break
}
}
var resultImage: UIImage = UIImage(data: data)!
if data.count < maxLength { return resultImage }
// Compress by size
var lastDataLength: Int = 0
while data.count > maxLength, data.count != lastDataLength {
lastDataLength = data.count
let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
height: Int(resultImage.size.height * sqrt(ratio)))
UIGraphicsBeginImageContext(size)
resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
resultImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
data = UIImageJPEGRepresentation(resultImage, compression)!
}
return resultImage
}