iOS图片压缩指定比例
2022-07-18 本文已影响0人
YimG
/**
- 压缩图片质量,返回值为可直接转化成UIImage对象的NSData对象
- aimLength: 目标大小,单位:字节(b)
- accuracyOfLength: 压缩控制误差范围(+ / -),本方法虽然给出了误差范围,但实际上很难确定一张图片是否能压缩到误差范围内,无法实现精确压缩。
*/
+ (NSData *)compressImageWithImage:(UIImage *)image aimWidth:(CGFloat)width aimLength:(NSInteger)length accuracyOfLength:(NSInteger)accuracy;
+ (NSData *)compressImageWithImage:(UIImage *)image aimWidth:(CGFloat)width aimLength:(NSInteger)length accuracyOfLength:(NSInteger)accuracy {
UIImage * newImage = [self imageWithImage:image scaledToSize:CGSizeMake(width, width * image.size.height / image.size.width)];
NSData * data = UIImageJPEGRepresentation(newImage, 1);
NSInteger imageDataLen = [data length];
if (imageDataLen <= length + accuracy) {
return data;
} else{
NSData * imageData = UIImageJPEGRepresentation( newImage, 0.99);
if (imageData.length < length + accuracy) {
return imageData;
}
CGFloat maxQuality = 1.0;
CGFloat minQuality = 0.0;
int flag = 0;
while (1) {
CGFloat midQuality = (maxQuality + minQuality)/2;
if (flag == 6) {
NSLog(@"************* %ld ******** %f *************",UIImageJPEGRepresentation(newImage, minQuality).length,minQuality);
return UIImageJPEGRepresentation(newImage, minQuality);
}
flag ++;
NSData * imageData = UIImageJPEGRepresentation(newImage, midQuality);
NSInteger len = imageData.length;
if (len > length+accuracy) {
NSLog(@"-----%d------%f------%ld-----",flag,midQuality,len);
maxQuality = midQuality;
continue;
}else if (len < length-accuracy){
NSLog(@"-----%d------%f------%ld-----",flag,midQuality,len);
minQuality = midQuality;
continue;
}else{
NSLog(@"-----%d------%f------%ld--end",flag,midQuality,len);
return imageData;
break;
}
}
}
}
//对图片尺寸进行压缩--
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用方法
BaseClass是自定义类文件NSobject,128是微信分享小程序所需最大尺寸
[BaseClass compressImageWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",@"数据url"]]]] aimWidth:图片宽度 aimLength:128*1024 accuracyOfLength:1024]