iOS 圖片壓縮方法

zhaoguian發表於2019-01-09

兩種圖片壓縮方法

兩種圖片壓縮方法:壓縮圖片質量(Quality),壓縮圖片尺寸(Size)。

  • 壓縮圖片質量

NSData *data = UIImageJPEGRepresentation(image, compression);
UIImage *resultImage = [UIImage imageWithData:data];
複製程式碼
  • 通過 UIImage 和 NSData 的相互轉化,減小 JPEG 圖片的質量來壓縮圖片。UIImageJPEGRepresentation:: 第二個引數 compression 取值 0.0~1.0,值越小表示圖片質量越低,圖片檔案自然越小
  • 壓縮圖片尺寸

UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
複製程式碼

給定所需的圖片尺寸 size,resultImage 即為原圖 image 繪製為 size 大小的圖片。

  • 壓縮圖片使圖片檔案小於指定大小

如果對圖片清晰度要求不高,要求圖片的上傳、下載速度快的話,上傳圖片前需要壓縮圖片。壓縮到什麼程度要看具體情況,但一般會設定一個圖片檔案最大值,例如 100 KB。可以用上訴兩種方法來壓縮圖片。假設圖片轉化來的 NSData 物件為 data,通過data.length即可得到圖片的位元組大小。

  • 壓縮圖片質量

比較容易想到的方法是,通過迴圈來逐漸減小圖片質量,直到圖片稍小於指定大小(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;
}
複製程式碼

這樣迴圈次數多,效率低,耗時長。 可以通過二分法來優化。

+ (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)!
}
複製程式碼

當圖片大小小於 maxLength,大於 maxLength * 0.9 時,不再繼續壓縮。最多壓縮 6 次,1/(2^6) = 0.015625 < 0.02,也能達到每次迴圈 compression 減小 0.02 的效果。這樣的壓縮次數比迴圈減小 compression 少,耗時短。需要注意的是,當圖片質量低於一定程度時,繼續壓縮沒有效果。也就是說,compression 繼續減小,data 也不再繼續減小。壓縮圖片質量的優點在於,儘可能保留圖片清晰度,圖片不會明顯模糊;缺點在於,不能保證圖片壓縮後小於指定大小。

壓縮圖片尺寸

與之前類似,比較容易想到的方法是,通過迴圈逐漸減小圖片尺寸,直到圖片稍小於指定大小(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 轉換為整數,防止繪製出的圖片有白邊

壓縮圖片尺寸可以使圖片小於指定大小,但會使圖片明顯模糊(比壓縮圖片質量模糊)。

  • 兩種圖片壓縮方法結合

如果要保證圖片清晰度,建議選擇壓縮圖片質量。如果要使圖片一定小於指定大小,壓縮圖片尺寸可以滿足。對於後一種需求,還可以先壓縮圖片質量,如果已經小於指定大小,就可得到清晰的圖片,否則再壓縮圖片尺寸。

+ (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
}
複製程式碼

參考資料

title: iOS 圖片壓縮方法

author: zhaoguian

time: 2019年01月09日16:55

簡書: www.jianshu.com/u/89307b77a…

相關文章