萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 圖片壓縮與縮放完整指南:3 種核心方法與最佳實踐

前言:兩大核心輸出函數

  • UIImageJPEGRepresentation(image, quality):JPEG 壓縮,`quality` 0.0~1.0,有損壓縮,適合照片
  • UIImagePNGRepresentation(image):PNG 無損壓縮,適合圖示、透明背景

壓縮策略 = **幾何縮放** 降低像素 + **編碼品質** 控制檔案大小。

方法一:等比縮放至目標尺寸(保持長寬比)


- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {
    CGSize srcSize = image.size;
    CGFloat srcW = srcSize.width, srcH = srcSize.height;
    CGFloat dstW = targetSize.width, dstH = targetSize.height;
    
    // 已小於目標,無需縮放
    if (srcW <= dstW && srcH <= dstH) return image;
    if (srcW == 0 || srcH == 0) return image;
    
    // 計算縮放比例(取較小者,保證完整顯示)
    CGFloat scale = MIN(dstW / srcW, dstH / srcH);
    CGFloat finalW = srcW * scale;
    CGFloat finalH = srcH * scale;
    
    // 繪製至新 Context
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(finalW, finalH), NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, finalW, finalH)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}

關鍵:`UIGraphicsBeginImageContextWithOptions(size, opaque, scale)` 第三參數傳 `0.0` 自動使用螢幕縮放因子(Retina 2x/3x)。

方法二:分類擴展:縮放 + 裁剪填滿

適用於頭像、封面圖:縮放至覆蓋目標區域,超出部分裁剪。


// UIImage+ResizeCrop.h
@interface UIImage (ResizeCrop)
- (UIImage *)scaleToSize:(CGSize)size;                    // 簡單拉伸填滿
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize; // 等比縮放+居中裁剪
@end

// UIImage+ResizeCrop.m
@implementation UIImage (ResizeCrop)

- (UIImage *)scaleToSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize {
    CGSize srcSize = self.size;
    if (CGSizeEqualToSize(srcSize, targetSize)) return self;
    
    CGFloat srcW = srcSize.width, srcH = srcSize.height;
    CGFloat dstW = targetSize.width, dstH = targetSize.height;
    
    // 計算縮放比例(取較大者,保證覆蓋)
    CGFloat scale = MAX(dstW / srcW, dstH / srcH);
    CGFloat scaledW = srcW * scale;
    CGFloat scaledH = srcH * scale;
    
    // 居中裁剪座標
    CGPoint origin = CGPointMake((dstW - scaledW) / 2.0, (dstH - scaledH) / 2.0);
    
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);
    [self drawInRect:CGRectMake(origin.x, origin.y, scaledW, scaledH)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}
@end

方法三:指定寬度等比壓縮(專案實戰常用)

給定目標寬度,高度自動等比,再配合 JPEG 品質控制檔案大小。


- (UIImage *)compressImage:(UIImage *)sourceImage toWidth:(CGFloat)targetWidth {
    CGSize srcSize = sourceImage.size;
    CGFloat srcW = srcSize.width, srcH = srcSize.height;
    if (srcW <= targetWidth) return sourceImage;
    
    CGFloat targetHeight = (targetWidth / srcW) * srcH;
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(targetWidth, targetHeight), NO, 0.0);
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}

// 完整壓縮流程:幾何縮放 + 品質壓縮 + 檔案大小檢查
- (NSData *)compressImageToMaxSize:(UIImage *)image maxBytes:(NSInteger)maxBytes maxWidth:(CGFloat)maxWidth {
    // 1. 幾何縮放
    UIImage *scaled = [self compressImage:image toWidth:maxWidth];
    
    // 2. 品質二分法壓縮
    CGFloat compression = 0.9;
    CGFloat minCompression = 0.1;
    NSData *data = UIImageJPEGRepresentation(scaled, compression);
    
    while (data.length > maxBytes && compression > minCompression) {
        compression -= 0.1;
        data = UIImageJPEGRepresentation(scaled, compression);
    }
    
    // 3. 仍超過大小,再次幾何縮放
    if (data.length > maxBytes) {
        CGFloat ratio = sqrt((CGFloat)maxBytes / data.length);
        CGFloat newW = scaled.size.width * ratio;
        scaled = [self compressImage:scaled toWidth:newW];
        data = UIImageJPEGRepresentation(scaled, 0.8);
    }
    
    return data;
}

效能關鍵:UIGraphicsBeginImageContextWithOptions vs UIGraphicsBeginImageContext

API支援 Retina透明度建議
UIGraphicsBeginImageContext❌ (1x)❌棄用
UIGraphicsBeginImageContextWithOptions✅ (scale 參數)✅ (opaque=NO)**唯一推薦**

記憶體管理與大圖處理

⚠️ 大圖解碼記憶體峰值
一張 4000×3000 JPEG 約 4MB,解碼後記憶體佔用 4000×3000×4 bytes ≈ 48MB。連續處理多張易 OOM。
✅ 方案:ImageIO 降級解碼

- (UIImage *)downsampleImageAtURL:(NSURL *)url toPointSize:(CGSize)pointSize scale:(CGFloat)scale {
    CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL);
    CFDictionaryRef options = (__bridge CFDictionaryRef)@{
        (id)kCGImageSourceCreateThumbnailWithTransform: @YES,
        (id)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
        (id)kCGImageSourceThumbnailMaxPixelSize: @(MAX(pointSize.width, pointSize.height) * scale)
    };
    CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options);
    CGImageSourceRelease(source);
    return [UIImage imageWithCGImage:thumbnail scale:scale orientation:UIImageOrientationUp];
}
直接解碼縮圖,記憶體峰值降低 90%+。

選型建議

需求推薦方法
單純縮放顯示方法一 + `UIGraphicsBeginImageContextWithOptions`
頭像/封面裁剪填滿方法二 `imageByScalingAndCroppingForSize:`
上傳限制檔案大小方法三雙重壓縮(幾何+品質)
大圖列表、相簿選擇器ImageIO `CGImageSourceCreateThumbnailAtIndex`
複雜濾鏡、編輯Core Image / Metal / GPUImage
copyright © 萬盛學電腦網 all rights reserved