iOS图片压缩

1.使用

 //缩略图
 //获取屏幕宽度(ScreenWidth)的15K(15*1024)大小的图片
 //图片大小与宽高要有一定比例,否者也是压缩不成功的

     NSData *thumImageData = [self compressImageWithImage:shareImage aimWidth:ScreenWidth aimLength:15*1024 accuracyOfLength:1024];
    CGFloat fData = [shareData length]/1024.0;
    UIImage * thumImage = [UIImage imageWithData:thumImageData];

2.实现

/**
 *  压缩图片质量,返回值为可直接转化成UIImage对象的NSData对象
 *  aimLength: 目标大小,单位:字节(b)
 *  accuracyOfLength: 压缩控制误差范围(+ / -),本方法虽然给出了误差范围,但实际上很难确定一张图片是否能压缩到误差范围内,无法实现精确压缩。
 */
- (NSData *)compressImageWithImage:(UIImage *)image aimWidth:(CGFloat)width aimLength:(NSInteger)length accuracyOfLength:(NSInteger)accuracy{
    UIImage * newImage = [self imageWithImage:image scaledToSize:CGSizeMake(width, width * image.size.height / image.size.width)];

    NSData  * data = UIImageJPEGRepresentation(newImage, 1);
    NSInteger imageDataLen = [data length];

    if (imageDataLen <= length + accuracy) {
        return data;
    }else{
        NSData * imageData = UIImageJPEGRepresentation( newImage, 0.99);
        if (imageData.length < length + accuracy) {
            return imageData;
        }

        CGFloat maxQuality = 1.0;
        CGFloat minQuality = 0.0;
        int flag = 0;

        while (1) {
            CGFloat midQuality = (maxQuality + minQuality)/2;

            if (flag == 6) {
                return UIImageJPEGRepresentation(newImage, minQuality);
            }
            flag ++;

            NSData * imageData = UIImageJPEGRepresentation(newImage, midQuality);
            NSInteger len = imageData.length;

            if (len > length+accuracy) {
                maxQuality = midQuality;
                continue;
            }else if (len < length-accuracy){
                minQuality = midQuality;
                continue;
            }else{
                return imageData;
                break;
            }
        }
    }
}

//对图片尺寸进行压缩--
- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值