- (UIImage*)compressImage:(UIImage*)image newWidth:(CGFloat)newImageWidth
{
if(!image)returnnil;
floatwidth = newImageWidth;
floatheight = image.size.height/(image.size.width/width);
//创建一个bitmap的context
//并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(CGSizeMake(width, height));
[imagedrawInRect:CGRectMake(0,0, width , height)];
//从当前context中创建一个改变大小后的图片
UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();
//使当前的context出堆栈
UIGraphicsEndImageContext();
returnnewImage;
}
- (NSData*)compressOriginalImage:(UIImage*)image toMaxDataSizeKBytes:(CGFloat)size{
NSData* data =UIImageJPEGRepresentation(image,1.0);
CGFloatdataKBytes = data.length/1024.0;
CGFloatmaxQuality =0.9f;
CGFloatlastData = dataKBytes;
while(dataKBytes > size && maxQuality >0.1f) {
maxQuality = maxQuality -0.1f;
data =UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length/1024.0;
if(lastData == dataKBytes) {
break;
}else{
lastData = dataKBytes;
}
}
returndata;
}