关于IOS中压缩图片

之前项目的图片压缩用的是UIImageJPEGRepresentation方法中的压缩因子进行压缩,但是图片失真会很严重,今天又花了点时间了解了下。

首先要说明一下UIImageJPEGRepresentation和UIImagePNGRepresentation,亲测后UIImagePNGRepresentation获取的图片会比UIImageJPEGRepresentation多出几十甚至几百KB的大小,所以在项目中有用到NSData转UIImage都是用的UIImageJPEGRepresentation。

关于压缩方法UIImageJPEGRepresentation 会使图片失真严重,现在用的是drawInRect重新绘制,以下是我项目中用到的方法(ps:也是网上找到的)


+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    
    CGSize imageSize = sourceImage.size;
    if(imageSize.width <= defineWidth){
        return sourceImage;
    }
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return newImage;
    
}

方法中的defineWidth 如果没有特别要求我基本都是传的屏幕的宽度,虽然不同大小手机可能会有偏差,但是总体的宽高比还是差不多,显示的效果也不会差太大


ps:微信发送图片中的原图大小计算是利用

      ALAssetRepresentation* representation = [asset defaultRepresentation];
        // 创建一个buffer保存图片数据
        uint8_t *buffer = (Byte*)malloc(representation.size);
        NSUInteger length = [representation getBytes:buffer fromOffset: 0.0  length:representation.size error:nil];
        
        // 将buffer转换为NSData object,然后释放buffer内存
        NSData *imageData = [[NSData alloc] initWithBytesNoCopy:buffer length:representation.size freeWhenDone:YES];

这边所获取到的imageData.length/1024就是图片的大小了,单位KB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值