关于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

猜你喜欢

转载自blog.csdn.net/u013677619/article/details/53784313