开发中关于图片处理的地方非常常见,这里分享一下我在处理图片压缩的时候遇到的坑,
图片压缩的2种方法
第一:
NSData *data = UIImageJPEGRepresentation(image,0.5)
或者来压缩,这里返回的data是在原图片上去掉很多信息(alpha通道等),并且格式为jpeg,当操作 newImage = [UIImage imageWithData:data]; newImage的imageData回比的data的字节大,这里属于正常的;
第二:drawInRect ,重绘
/**
压缩上传图片
@param image 原图片
@param maxLength 需要上传的图片文件大小
@return data
*/
+(NSData *)imageCompressWith: (UIImage *)image maxLength: (CGFloat )maxLength{
NSData *imageData = UIImageJPEGRepresentation(image, 1);
if (imageData.length < maxLength) return imageData;
CGFloat max = 1;
CGFloat min = 0;
UIImage *newImage = image;
NSData * data;
for (int i = 0; i < 6; i ++) {
CGFloat compression = (max + min) * 0.5;
data = UIImageJPEGRepresentation(newImage, compression);
CGFloat length = data.length;
if (length < maxLength * 0.9) {
min = compression;
}else if (length > maxLength) {
max = compression;
}else {
break;
}
}
if (data.length < maxLength) return data;
newImage = [UIImage imageWithData:data];
// 重绘
for (int i = 1; i < 6; i ++) {
int width = image.size.width * (1-i*0.1);
int height = image.size.height * (1-i*0.1);
CGSize size = CGSizeMake(width, height);
UIGraphicsBeginImageContext(size);
[newImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(newImage, 1);
if (data.length < maxLength) {
break;
}
}
return data;
}
用户上传的图片可能乱七八糟,大小不一,我们采用一个固定的压缩参数去压缩图片总是会有问题
上面代码是我最终采用的方法,这里返回的NSData就可以拿来直接上传给咱们的服务器了