先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后在判断图片数据大小,传入范围maxSize = 100 ,大于的再压缩,小的就保持原样
- (NSData *)compressionImageToDataTargetWH:(CGFloat)targetWH maxFileSize:(NSInteger)maxFileSize
{
if (targetWH <= 0) {
targetWH = 1024;
}
//缩
CGSize newSize = CGSizeMake(self.size.width, self.size.height);
CGFloat tempHeight = newSize.height / targetWH;
CGFloat tempWidth = newSize.width / targetWH;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(self.size.width / tempWidth, self.size.height / tempWidth);
}
else if (tempHeight > 1.0 && tempWidth < tempHeight){
newSize = CGSizeMake(self.size.width / tempHeight, self.size.height / tempHeight);
}
UIGraphicsBeginImageContext(newSize);
[self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//压
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
NSData *imageData = UIImageJPEGRepresentation(newImage, compression);
while (imageData.length / 1000 > maxFileSize && compression > maxCompression) {
compression -= 0.1;
imageData = UIImageJPEGRepresentation(newImage, compression);
}
return imageData;
}
网友评论