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;
}
| API | 支援 Retina | 透明度 | 建議 |
|---|---|---|---|
| UIGraphicsBeginImageContext | ❌ (1x) | ❌ | 棄用 |
| UIGraphicsBeginImageContextWithOptions | ✅ (scale 參數) | ✅ (opaque=NO) | **唯一推薦** |
- (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 |