在日常IOS開發中,感覺圖片尺寸太大,想壓縮成小一點像素的。那么該如何做呢?本文通過“壓縮”兩個概念及實例來告訴大家如何進行圖片壓縮處理才是最好的。
1、確圖片的壓縮的概念:
“壓” 是指文件體積變小,但是像素數不變,長寬尺寸不變,那么質量可能下降。
“縮” 是指文件的尺寸變小,也就是像素數減少,而長寬尺寸變小,文件體積同樣會減小。
2、圖片壓的處理
對于“壓”的功能,我們可以使用UIImageJPEGRepresentation或UIImagePNGRepresentation方法實現,
如代碼:
//圖片壓
- (UIImage *)imageCompression:(UIImage *)img{
// UIImage *image = [UIImage imageNamed:@"HD"];
//第一個參數是圖片對象,第二個參數是壓的系數,其值范圍為0~1。
NSData * imageData = UIImageJPEGRepresentation(img, 0.7);
UIImage * newImage = [UIImage imageWithData:imageData];
return newImage;
}
2.1關于PNG和JPEG格式壓縮
UIImageJPEGRepresentation函數需要兩個參數:圖片的引用和壓縮系數而UIImagePNGRepresentation只需要圖片引用作為參數.
UIImagePNGRepresentation(UIImage image)要比UIImageJPEGRepresentation(UIImage image, 1.0)返回的圖片數據量大很多.
同樣的一張照片, 使用UIImagePNGRepresentation(image)返回的數據量大小為200K,而 UIImageJPEGRepresentation(image, 1.0)返回的數據量大小只為150K,比前者少了50K.
如果對圖片的清晰度要求不是極高,建議使用UIImageJPEGRepresentation,可以大幅度降低圖片數據量.比如,剛才拍攝的圖片,通過調用UIImageJPEGRepresentation(image, 1.0)讀取數據時,返回的數據大小為140K,但更改壓縮系數為0.5再讀取數據時,返回的數據大小只有11K,大大壓縮了圖片的數據量,而且清晰度并沒有相差多少,圖片的質量并沒有明顯的降低。因此,在讀取圖片數據內容時,建議優先使用UIImageJPEGRepresentation,并可根據自己的實際使用場景,設置壓縮系數,進一步降低圖片數據量大小。
提示:壓縮系數不宜太低,通常是0.3~0.7,過小則可能會出現黑邊等。
3、圖片“縮”處理
通過[image drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)]可以進行圖片“縮”的功能。
- (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); 是1的功能。
這個 [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)] 是2的功能。
總結
所以,這倆得結合使用來滿足需求,不然你一味的用1,導致,圖片模糊的不行,但是尺寸還是很大。
以上就是在IOS中壓縮圖片處理的詳細介紹及實例,希望對大家學習IOS開發有所幫助。