/*根据url返回UIimage*/
+(UIImage*) getImageFromURL:(NSString*)fileURL
{
UIImage* result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImageimageWithData:data];
returnresult;
}
#pragma mark - 压缩图片---小于32KB
+ (UIImage*)compressImage:(UIImage*)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloatcompression =1;
NSData*data =UIImageJPEGRepresentation(image, compression);
if(data.length< maxLength)returnimage;
CGFloatmax =1;
CGFloatmin =0;
for(inti =0; i <6; ++i) {
compression = (max + min) /2;
data =UIImageJPEGRepresentation(image, compression);
if(data.length< maxLength *0.9) {
min = compression;
}elseif(data.length> maxLength) {
max = compression;
}else{
break;
}
}
UIImage*resultImage = [UIImageimageWithData:data];
if(data.length< maxLength)returnresultImage;
// Compress by size
NSUIntegerlastDataLength =0;
while(data.length> maxLength && data.length!= lastDataLength) {
lastDataLength = data.length;
CGFloatratio = (CGFloat)maxLength / data.length;
CGSizesize =CGSizeMake((NSUInteger)(resultImage.size.width*sqrtf(ratio)),
(NSUInteger)(resultImage.size.height*sqrtf(ratio)));// Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImagedrawInRect:CGRectMake(0,0, size.width, size.height)];
resultImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data =UIImageJPEGRepresentation(resultImage, compression);
}
returnresultImage;
}
网友评论