iOS之图片压缩

在iOS应用中,用户上传的图片通常需要进行压缩后才能进行上传。

图片的压缩其实是两个不同的概念:

  1. 是 “压” 文件体积变小,但是像素数不变,长宽尺寸不变,那么质量可能下降。
  2. 是 “缩” 文件的尺寸变小,也就是像素数减少。长宽尺寸变小,文件体积同样会减小。

代码片段:

  • 压缩图片文件大小(UIImageJPEGRepresentation(image, 0.0实现的是“压”的功能。)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    +(UIImage *)image:(UIImage *)image toMaxSize:(CGFloat)size
    {
    UIImage *resultImage = image;
    NSData *data = UIImageJPEGRepresentation(resultImage, 1);
    NSUInteger lastDataLength = 0;

    while (data.length > size && data.length != lastDataLength) {
    lastDataLength = data.length;
    CGFloat imgRatio = (CGFloat)size / data.length;
    CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(imgRatio)),
    (NSUInteger)(resultImage.size.height * sqrtf(imgRatio))); // Use NSUInteger to prevent white blank
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    data = UIImageJPEGRepresentation(resultImage, 1);
    }

    UIImage *targetImg = [[UIImage alloc] initWithData:data];
    return targetImg;
    }
  • 缩小图片到指定size ([sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)]是“缩”的功能)

    1
    2
    3
    4
    5
    6
    7
    -(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
    }