由于图片加载如果图片内存太大的话第一次下载比较耗时,尤其是现在智能手机拍出的照片清晰度越来越高,内存越来越大,所以我们在图片上传的时候就需要做压缩处理!
下面就简要说一下我的处理压缩文件的方式:
新建一个分类:
+(NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
//进行图像尺寸的压缩
CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
CGFloat width = imageSize.width; //图片宽度
CGFloat height = imageSize.height; //图片高度
//1.宽高大于1280(宽高比不按照2来算,按照1来算)
if (width>1280 && height>1280) {
if (width>height) {
CGFloat scale = height/width;
width = 1280;
height = width*scale;
}else{
CGFloat scale = width/height;
height = 1280;
width = height*scale;
}
//2.宽大于1280高小于1280
}else if(width>1280 && height<1280){
CGFloat scale = height/width;
width = 1280;
height = width*scale;
//3.宽小于1280高大于1280
}else if(width<1280 && height>1280){
CGFloat scale = width/height;
height = 1280;
width = height*scale;
//4.宽高都小于1280
}else{
}
UIGraphicsBeginImageContext(CGSizeMake(width, height));
[sourceImage drawInRect:CGRectMake(0,0,width,height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//进行图像的画面质量压缩
NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
if (data.length>100*1024) {
if (data.length>1024*1024) {//1M以及以上
data=UIImageJPEGRepresentation(newImage, 0.7);
}else if (data.length>512*1024) {//0.5M-1M
data=UIImageJPEGRepresentation(newImage, 0.8);
}else if (data.length>200*1024) {
//0.25M-0.5M
data=UIImageJPEGRepresentation(newImage, 0.9);
}
}
return data;
}
这样当图片再次上传的时候,调用这个方法对image做一次压缩处理,图片就会小很多了!
描述不是很好,大家试试吧!
--------------------
网友评论