正确图片压缩方式(清晰度不会太大影响)
/**
压缩图片保证不旋转
@param image 原图
@param size 限制大小,单位:M
@return 压缩后的图片数据
*/
- (NSData *)zipImageWithImage:(UIImage *)image maxSize:(CGFloat)size{
if (!image) {
return nil;
}
CGFloat maxFileSize = size*1024*1024;
CGFloat compression = 0.9f;
NSData *compressedData = UIImageJPEGRepresentation(image, compression);
NSLog(@"%lu",(unsigned long)compressedData.length);
if ([compressedData length]> maxFileSize) {
//开始压缩直到小于 maxFileSize
while ([compressedData length] > maxFileSize) {
compression *= 0.9;
compressedData = UIImageJPEGRepresentation([self compressImage:image newWidth:image.size.width*compression], compression);
}
}else{
//原图不需要压缩
compressedData = UIImagePNGRepresentation(image);
}
NSLog(@"%lu",(unsigned long)compressedData.length);
return compressedData;
}
- (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth{
if (!image) return nil;
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float width = newImageWidth;
float height = image.size.height/(image.size.width/width);
float widthScale = imageWidth /width;
float heightScale = imageHeight /height;
UIGraphicsBeginImageContext(CGSizeMake(width, height));
if (widthScale > heightScale) {
[image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
} else {
[image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
}
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
需要注意的:
方法1得到的NSData数据直接上传,不要再做其他无用功,例如
//将原图片压缩到1.0M以下
NSData * zipData=[self zipImageWithImage: image maxSize: 1.0 ];
//得到压缩后的图片
UIImage * newImage=[UIImage imageWithData:data];
//这一步会导致上传的数据变大(等于没有压缩,甚至变更大)
1.NSData * data5=UIImageJPEGRepresentation(newImage, 1.0);
2.NSData * data6=UIImagePNGRepresentation(newImage);
data5 和 data6 相比 zipData 会变大,
1方法使原图1.3M左右变为2.1M
2方法使原图1.3M左右变为8M
如果这时候上传的是data5或者data6,等于没有压缩啊~~~
项目中就遇到这样的坑,因为压缩图片用的工具类返回的不是zipData而是newImage,然后就上传了data6!!!!
尼玛还选择了个最大的,我就@#¥%……&*……%¥#@#¥