ios中系統(tǒng)為我們提供了兩種壓縮圖片的方法:
UIImagePNGRepresentation(UIImage*__nonnullimage);// return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format]
UIImageJPEGRepresentation(UIImage*__nonnullimage,CGFloatcompressionQuality);//return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)
UIImageJPEGRepresentation:方法需要兩個(gè)參數(shù):圖片的引用和壓縮系數(shù);
UIImagePNGRepresentation :方法僅僅需要一個(gè)參數(shù):圖片的引用;
>
UIImagePNGRepresentation:耗時(shí)更多,圖片數(shù)據(jù)量更大,讀取照片數(shù)據(jù)的時(shí)候可能會(huì)照成卡頓;
>
兩者返回的都是NSData類型;
在實(shí)際開(kāi)發(fā)中,可能會(huì)遇到從手機(jī)相冊(cè)中選擇圖片的需求,選擇圖片這個(gè)過(guò)程是一個(gè)消耗性能的過(guò)程,取決于手機(jī)圖片的大小,如果手機(jī)像素非常高,圖片的尺寸非常大,這個(gè)時(shí)候就會(huì)變得很消耗性能;
以上兩種方法雖然都可能達(dá)到壓縮圖片的需求,但是可能會(huì)照成圖片的失真;
下面提供另一種方法:根據(jù)圖片從新繪制一張出來(lái),不會(huì)失真,只是改變圖片大小,比如之前是50005000的分辨率,這個(gè)時(shí)候你壓縮后可能就只有500500,不會(huì)失真,只會(huì)改變大小,建議使用;
- (UIimage *)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Swift版:
func useImage(image: UIImage) -> NSData {
//實(shí)現(xiàn)等比例縮放
let hfactor = image.size.width / screnWidth;
let vfactor = image.size.height / screnHeight;
let factor = fmax(hfactor, vfactor);
//畫布大小
let newWith: CGFloat = image.size.width / factor
let newHeigth: CGFloat = image.size.height / factor
let newSize = CGSize(width: newWith, height: newHeigth)
UIGraphicsBeginImageContext(newSize)
image.drawInRect(CGRect(x: 0, y: 0, width: newWith, height: newHeigth))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//圖像壓縮
let newImageData = UIImageJPEGRepresentation(newImage, 0.5)
return newImageData!
}