支持网络和本地图片压缩
实现思路:先压缩图片的大小,再压缩图片的质量。
网络图片转image对象:
NSData *temdata = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"图片链接地址"]];
UIImage *image = [UIImage imageWithData:temdata];
data转image:
self.imageView.image = [UIImage imageWithData:data];
图片压缩代码完整实现如下:
@param image 图片对象
@param maxLength 最大体积KB为单位
@return 压缩后的图片data数据
压缩图片至最大体积为maxLength
+ (NSData*)compressImageQuality:(UIImage*)image toByte:(NSInteger)maxLength {
//先压缩size,再压缩质量
UIImage *newimage = [self thumbnailWithKeepScale:image size:CGSizeMake(150, 150)];
NSData *data = UIImageJPEGRepresentation(newimage, 1.0);
if (data.length>maxLength*1024) {
UIImage *image1 = [self compressImage:newimage toByte:maxLength];
NSData *data = UIImageJPEGRepresentation(image1, 1.0);
return data;
}else {
return data;
}
}
根据最新的size,保持原图的宽高比,生成一个缩略图
+ (UIImage *)thumbnailWithKeepScale:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image) {
newimage = nil;
}
else{
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height) {
rect.size.width = asize.height*oldsize.width/oldsize.height;
rect.size.height = asize.height;
rect.origin.x = 0;
rect.origin.y = 0;
}
else{
rect.size.width = asize.width;
rect.size.height = asize.width*oldsize.height/oldsize.width;
rect.origin.x = 0;
rect.origin.y = 0;
}
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, rect.size.width, rect.size.height));
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
循环压缩图片质量
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return resultImage;
NSUInteger temLength = 0;
while (data.length > maxLength && data.length != temLength) {
temLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio)));
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, 100, 100)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}