压缩图片,如果图片大于100kb,就循环压缩

// 压缩图片,如果图片大于100kb,就循环压缩
+ (NSData *)compressionWithImage:(UIImage *)image{

// 先按宽度压缩
UIImage *newImage = [image resizeImageGreaterThan:480];

NSData *data;
float quality = 1.0f;
if (UIImageJPEGRepresentation(newImage, quality)) {
data = UIImageJPEGRepresentation(newImage, quality);
while (data.length / 1024.0f > 100 && quality > 0.5) {
quality -= 0.1f;
data = UIImageJPEGRepresentation(newImage, quality);
}
}

if (data == nil) {
data = UIImageJPEGRepresentation(newImage, 0.5);
}

return data;
}


----mark
// 这里是UIImage的一个扩展,按宽度压缩
#import "UIImage+Resize.h"

@implementation UIImage (Resize)

- (UIImage*)resizeImageGreaterThan:(CGFloat)maxL {
UIImage * res;
UIImage * img = self;
res = img;
float height = img.size.height;
float width = img.size.width;
float bigger = height > width ? height : width;
float coefficient = 1.0;
int maxPix = maxL;
if (bigger > maxPix) {
coefficient = maxPix / bigger;
res = [img resizeImageWithNewSize:CGSizeMake(width * coefficient, height * coefficient)];
}
return res;
}

- (UIImage*)resizeImageWithNewSize:(CGSize)newSize
{
CGFloat newWidth = newSize.width;
CGFloat newHeight = newSize.height;
// Resize image if needed.
float width = self.size.width;
float height = self.size.height;
// fail safe
if (width == 0 || height == 0)
return self;

//float scale;

if (width != newWidth || height != newHeight) {
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[self drawInRect:CGRectMake(0, 0, newWidth, newHeight)];

UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//NSData *jpeg = UIImageJPEGRepresentation(image, 0.8);
return resized;
}
return self;
}


@end


#import <UIKit/UIKit.h>

@interface UIImage (Resize)

/*
* brife 缩放图片
* maxL 图片的高度
*/
- (UIImage*)resizeImageGreaterThan:(CGFloat)maxL;
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值