分兩部分,1縮小圖片大小2減弱圖片質量
@1. 縮小圖片大小
首先我們弄個catogory
//頭文件
@interface UIImage (Compress)
- (UIImage *)compressedImage;
@end
//mm文件
#define MAX_IMAGEPIX 200.0 // max pix 200.0px
#define MAX_IMAGEDATA_LEN 200.0 // max data length 5K
@implementation UIImage (Compress)
- (UIImage *)compressedImage {
CGSize imageSize = self.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width <= MAX_IMAGEPIX && height <= MAX_IMAGEPIX) {
// no need to compress.
return self;
}
if (width == 0 || height == 0) {
// void zero exception
return self;
}
UIImage *newImage = nil;
CGFloat widthFactor = MAX_IMAGEPIX / width;
CGFloat heightFactor = MAX_IMAGEPIX / height;
CGFloat scaleFactor = 0.0;
if (widthFactor > heightFactor)
scaleFactor = heightFactor; // scale to fit height
else
scaleFactor = widthFactor; // scale to fit width
CGFloat scaledWidth = width * scaleFactor;
CGFloat scaledHeight = height * scaleFactor;
CGSize targetSize = CGSizeMake(scaledWidth, scaledHeight);
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[self drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
封裝函數為:
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
@2.減弱圖片質量
NSData *dataImg = UIImageJPEGRepresentation(img, 0.0001);
在Iphone上有兩種讀取圖片數據的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation. UIImageJPEGRepresentation函數需要兩個參數:圖片的引用和壓縮系數.而UIImagePNGRepresentation只需要圖片引用作為參數.通過在實際使用過程中,比較發現: UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的圖片數據量大很多.譬如,同樣是讀取攝像頭拍攝的同樣景色的照片, UIImagePNGRepresentation()返回的數據量大小為199K ,而 UIImageJPEGRepresentation(UIImage* image, 1.0)返回的數據量大小只為140KB,比前者少了50多KB.如果對圖片的清晰度要求不高,還可以通過設置 UIImageJPEGRepresentation函數的第二個參數,大幅度降低圖片數據量.譬如,剛才拍攝的圖片, 通過調用UIImageJPEGRepresentation(UIImage* image, 1.0)讀取數據時,返回的數據大小為140KB,但更改壓縮系數后,通過調用UIImageJPEGRepresentation(UIImage* image, 0.5)讀取數據時,返回的數據大小只有11KB多,大大壓縮了圖片的數據量 ,而且從視角角度看,圖片的質量並沒有明顯的降低.因此,在讀取圖片數據內容時,建議優先使用UIImageJPEGRepresentation,並可根據自己的實際使用場景,設置壓縮系數,進一步降低圖片數據量大小