iOS中图片压缩成指定的大小

iOS中,我们为了节省内存,需要对图片来进行处理,来优化程序,提高程序的效率,下面是一个根据自己的要求来重新设置图片的大小:

+(NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)maxLength
{
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
//NSLog(@“Before compressing quality, image size = %ld KB”,data.length/1024);
if (data.length < maxLength) return data;

CGFloat max = 1;
CGFloat min = 0;

//通过二分法优化
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
//NSLog(@“Compression = %.1f”, compression);
//NSLog(@“In compressing quality loop, image size = %ld KB”, data.length / 1024);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
//NSLog(@“After compressing quality, image size = %ld KB”, data.length / 1024);
if (data.length < maxLength) return data;
UIImage *resultImage = [UIImage imageWithData:data];
// Compress by size
NSUInteger lastDataLength = 0;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
//NSLog(@“Ratio = %.1f”, ratio);
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
//NSLog(@“In compressing size loop, image size = %ld KB”, data.length / 1024);
}
//NSLog(@“After compressing size loop, image size = %ld KB”, data.length / 1024);
return data;
}

你可能感兴趣的:(iOS,—,优化)