提到圖片壓縮,很多人第一反應就是調個品質係數。但其實「壓」和「縮」是兩件完全不同的事,搞混了就會出現「圖片糊了但檔案還是很大」的尷尬局面。
系統提供了現成的方法:
//圖片壓 - (void)_imageCompression{ UIImage *image = [UIImage imageNamed:@"HD"]; //第一個參數是圖片對象,第二個參數是壓的系數,其值范圍為0~1。 NSData * imageData = UIImageJPEGRepresentation(image, 0.7); UIImage * newImage = [UIImage imageWithData:imageData]; }
兩者的函數簽名不同:UIImageJPEGRepresentation 需要「圖片 + 壓縮係數」兩個參數,UIImagePNGRepresentation 只要圖片。而 UIImagePNGRepresentation(image) 吐出來的資料量,往往遠大於 UIImageJPEGRepresentation(image, 1.0)。
同一張照片做個對比就很直觀:PNG 編碼約 200K,JPEG 品質 1.0 只要 150K,硬省 50K。如果把係數降到 0.5,同一張剛拍好的照片能從 140K 掉到 11K,而肉眼幾乎看不出差異。
所以結論很清楚:只要不是對清晰度有極端要求的場景(例如設計素材、醫療影像),優先選 JPEG,並依場景調整係數。
提示:係數別壓得太狠,實務上 0.3~0.7 是安全區間,再低就可能出現黑邊等異常。
核心只有一句 [image drawInRect:...],但需要自己算好等比與居中,否則會變形:
/** * 圖片壓縮到指定大小 * @param targetSize 目標圖片的大小 * @param sourceImage 源圖片 * @return 目標圖片 */ - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage { UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) scaleFactor = widthFactor; // scale to fit height else scaleFactor = heightFactor; // scale to fit width scaledWidth= width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); // this will crop CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width= scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); if(newImage == nil) NSLog(@"could not scale image"); //pop the context to get back to the default UIGraphicsEndImageContext(); return newImage; }
對應關係是這樣的:UIImageJPEGRepresentation(image, 0.0) 和 UIImagePNGRepresentation(image) 屬於「壓」;[sourceImage drawInRect:CGRectMake(0,0,targetWidth,targetHeight)] 屬於「縮」。
上傳頭像這類場景,正確順序是「先縮後壓」:先用 drawInRect 把尺寸降到目標解析度,再用 JPEG 編碼調一次係數。只壓不縮,你會得到一張依然巨大但已經發糊的圖;只縮不壓,則可能因為 PNG 編碼而浪費流量。兩者搭配,才能同時把尺寸和體積都控制住。