#define COMMON_COMPRSSION_FACTOR 0.8f //1.设置固定的压缩系数0~1
#define MAX_IMAGE_SIZE (1 * 1024 * 1024)//2.服务器能接受的最大的图片大小1024*1024是1M
@implementation SACompressUtil
+(NSData *)compressImageWithOriginalSize:(UIImage *)originalImage {
CGFloat compression = COMMON_COMPRSSION_FACTOR;
CGFloat maxCompression = 0.1f;
long maxFileSize = MAX_IMAGE_SIZE;
NSData *imageData = UIImageJPEGRepresentation(originalImage, compression);//3.正常压缩图片
while ([imageData length] > maxFileSize && compression > maxCompression)//4.如果传入的图片的大小大于1M,并且压缩系数大于0.1,则符合条件
{
compression -= 0.1;//将压缩系数-0.1(从0.8开始减),越小则图片压缩越严重
imageData = UIImageJPEGRepresentation(originalImage, compression);//通过这个方法压缩图片(两个参数,uimage,压缩系数)
}
return imageData;
}
原文:http://www.cnblogs.com/dcy123/p/5363914.html