1.使用
NSData *thumImageData = [self compressImageWithImage:shareImage aimWidth:ScreenWidth aimLength:15*1024 accuracyOfLength:1024];
CGFloat fData = [shareData length]/1024.0;
UIImage * thumImage = [UIImage imageWithData:thumImageData];
2.实现
- (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) {
return UIImageJPEGRepresentation(newImage, minQuality);
}
flag ++;
NSData * imageData = UIImageJPEGRepresentation(newImage, midQuality);
NSInteger len = imageData.length;
if (len > length+accuracy) {
maxQuality = midQuality;
continue;
}else if (len < length-accuracy){
minQuality = midQuality;
continue;
}else{
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;
}