OC版本
+ (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;
}
SWIFT版本
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
}