-(UIImage *)compressImage:(UIImage *)image
{
@autoreleasepool {
//压缩图片尺寸
float scales = image.size.height / image.size.width;
UIImage *normalImg;
NSData *newData;
/*
如果需要改动被压大小,调整scale,而不是kk或aa
*/
if (image.size.width > 1000 || image.size.height > 1000) {//这里的1000就是scale,所有的都要随着改变
if (scales > 1) {
CGSize newSize = CGSizeMake(1000 / scales, 1000);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
normalImg = UIGraphicsGetImageFromCurrentImageContext();
}else {
CGSize newSize = CGSizeMake(1000 ,1000 * scales);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
normalImg = UIGraphicsGetImageFromCurrentImageContext();
}
}
else {
normalImg=image;
}
CGSize newSize = CGSizeMake(normalImg.size.width, normalImg.size.height);
UIGraphicsBeginImageContext(newSize);
[normalImg drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//图片压缩系数
float kk = 1.0f;
//图片压缩系数变化步长(可变)
float aa = 0.1f;
//压缩后的大小
int mm;
mm=(int)UIImageJPEGRepresentation(newImage, kk).length;
while (mm/1024 > 100) {
if (kk > aa+aa/10) {
kk -= aa;
mm = (int)UIImageJPEGRepresentation(newImage, kk).length;
}else{
aa /= 10;
}
}
newData = UIImageJPEGRepresentation(newImage, kk);//最后压缩结果
NSLog(@"11111------------===%ld",(long)newData.length/1024);
if (newData.length/1024 > 100) {
return nil;
}else{
UIImage *image = [UIImage imageWithData:newData];
return image;
}
}
}