[iOS 圖片壓縮方法]
(http://www.cnblogs.com/silence-cnblogs/p/6346729.html)
iOS 圖片壓縮方法
兩種圖片壓縮方法
兩種壓縮圖片的方法:壓縮圖片質(zhì)量(Quality)荷逞,壓縮圖片尺寸(Size)。
壓縮圖片質(zhì)量
NSData *data = UIImageJPEGRepresentation(image, compression);
UIImage *resultImage = [UIImage imageWithData:data];
通過 UIImage 和 NSData 的相互轉(zhuǎn)化粹排,減小 JPEG 圖片的質(zhì)量來壓縮圖片种远。UIImageJPEGRepresentation:: 第二個(gè)參數(shù) compression 取值 0.0~1.0,值越小表示圖片質(zhì)量越低顽耳,圖片文件自然越小坠敷。
壓縮圖片尺寸
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
給定所需的圖片尺寸 size妙同,resultImage 即為原圖 image 繪制為 size 大小的圖片。
壓縮圖片使圖片文件小于指定大小
如果對(duì)圖片清晰度要求不高膝迎,要求圖片的上傳粥帚、下載速度快的話,上傳圖片前需要壓縮圖片限次。壓縮到什么程度要看具體情況芒涡,但一般會(huì)設(shè)定一個(gè)圖片文件最大值,例如 100 KB卖漫》丫。可以用上訴兩種方法來壓縮圖片。假設(shè)圖片轉(zhuǎn)化來的 NSData 對(duì)象為 data懊亡,通過data.length
即可得到圖片的字節(jié)大小依啰。
壓縮圖片質(zhì)量
比較容易想到的方法是,通過循環(huán)來逐漸減小圖片質(zhì)量店枣,直到圖片稍小于指定大小(maxLength)。
+ (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression); while (data.length > maxLength && compression > 0)
{ compression -= 0.02;
data = UIImageJPEGRepresentation(image, compression);
// When compression less than a value, this code dose not work } UIImage *resultImage = [UIImage imageWithData:data]; return resultImage;}
這樣循環(huán)次數(shù)多叹誉,效率低鸯两,耗時(shí)長。
可以通過二分法來優(yōu)化长豁。
+ (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;
}
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)!}
當(dāng)圖片大小小于 maxLength钧唐,大于 maxLength * 0.9 時(shí),不再繼續(xù)壓縮匠襟。最多壓縮 6 次钝侠,1/(2^6) = 0.015625 < 0.02,也能達(dá)到每次循環(huán) compression 減小 0.02 的效果酸舍。這樣的壓縮次數(shù)比循環(huán)減小 compression 少帅韧,耗時(shí)短。需要注意的是啃勉,當(dāng)圖片質(zhì)量低于一定程度時(shí)忽舟,繼續(xù)壓縮沒有效果。也就是說淮阐,compression 繼續(xù)減小叮阅,data 也不再繼續(xù)減小。壓縮圖片質(zhì)量的優(yōu)點(diǎn)在于泣特,盡可能保留圖片清晰度浩姥,圖片不會(huì)明顯模糊;缺點(diǎn)在于状您,不能保證圖片壓縮后小于指定大小勒叠。
壓縮圖片尺寸
與之前類似兜挨,比較容易想到的方法是,通過循環(huán)逐漸減小圖片尺寸缴饭,直到圖片稍小于指定大小(maxLength)暑劝。具體代碼省略。同樣的問題是循環(huán)次數(shù)多颗搂,效率低担猛,耗時(shí)長《猓可以用二分法來提高效率傅联,具體代碼省略。這里介紹另外一種方法疚察,比二分法更好蒸走,壓縮次數(shù)少,而且可以使圖片壓縮后剛好小于指定大小(不只是 < 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 來繪制岛抄。用原圖繪制别惦,壓縮后圖片更接近指定大小,但是壓縮次數(shù)較多夫椭,耗時(shí)較長掸掸。一張大小為 6064 KB 的圖片,壓縮圖片尺寸蹭秋,原圖繪制與新圖繪制結(jié)果如下
指定大小(KB)
原圖繪制壓縮后大小(KB)
原圖繪制壓縮次數(shù)
新圖繪制壓縮后大小(KB)
新圖繪制壓縮次數(shù)
兩種繪制方法壓縮后大小很接近扰付,與指定大小也很接近,但原圖繪制壓縮次數(shù)可達(dá)到新圖繪制壓縮次數(shù)的兩倍仁讨。建議使用新圖繪制羽莺,減少壓縮次數(shù)。壓縮后圖片明顯比壓縮質(zhì)量模糊陪竿。
需要注意的是繪制尺寸的代碼CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
禽翼,每次繪制的尺寸 size,要把寬 width 和 高 height 轉(zhuǎn)換為整數(shù)族跛,防止繪制出的圖片有白邊闰挡。
壓縮圖片尺寸可以使圖片小于指定大小,但會(huì)使圖片明顯模糊(比壓縮圖片質(zhì)量模糊)礁哄。
兩種圖片壓縮方法結(jié)合
如果要保證圖片清晰度长酗,建議選擇壓縮圖片質(zhì)量。如果要使圖片一定小于指定大小桐绒,壓縮圖片尺寸可以滿足夺脾。對(duì)于后一種需求之拨,還可以先壓縮圖片質(zhì)量,如果已經(jīng)小于指定大小咧叭,就可得到清晰的圖片蚀乔,否則再壓縮圖片尺寸。
+ (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}
Swift 代碼已上傳 GitHub:https://github.com/Silence-GitHub/CompressImageDemo
轉(zhuǎn)載請(qǐng)注明出處:http://www.cnblogs.com/silence-cnblogs/p/6346729.html