iOS中图片压缩方法
2017-03-24 本文已影响88人
King_Liu
ios中系统为我们提供了两种压缩图片的方法:
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:方法需要两个参数:图片的引用和压缩系数;
UIImagePNGRepresentation :方法仅仅需要一个参数:图片的引用;
>
UIImagePNGRepresentation:耗时更多,图片数据量更大,读取照片数据的时候可能会照成卡顿;
>
两者返回的都是NSData类型;
在实际开发中,可能会遇到从手机相册中选择图片的需求,选择图片这个过程是一个消耗性能的过程,取决于手机图片的大小,如果手机像素非常高,图片的尺寸非常大,这个时候就会变得很消耗性能;
以上两种方法虽然都可能达到压缩图片的需求,但是可能会照成图片的失真;
下面提供另一种方法:根据图片从新绘制一张出来,不会失真,只是改变图片大小,比如之前是50005000的分辨率,这个时候你压缩后可能就只有500500,不会失真,只会改变大小,建议使用;
- (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 {
//实现等比例缩放
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!
}