图片压缩,别问我是谁,请叫我雷锋

First. You should建立一个UIImage的category,叫Helper

Second.   so,UIImage+Helper.h中:

//图片压缩

- (UIImage *)compressedImage;

//将Image转换成NSData

- (NSData *)imageData;

UIImage+Helper.m中:

#import "UIImage+Helper.h"

#define MAX_IMAGE_WIDTH_PIX 800.0    //max pix 200.0px

#define MAX_IMAGE_HEIGHT_PIX 800.0

#define MAX_IMAGEDATA_LEN 50000.0

@implementation UIImage (Helper)

- (UIImage *)compressedImage{

    CGSize imageSize = self.size;

    CGFloat width = imageSize.width;

    CGFloat height = imageSize.height;

    

    if (width <= MAX_IMAGE_WIDTH_PIX && height <= MAX_IMAGE_HEIGHT_PIX) {

        //no need to compress.

        return self;

    }

    if (width == 0 || height == 0) {

        //void zero exception

        return self;

    }

    UIImage * newImage = nil;

    CGFloat widthFactor = MAX_IMAGE_WIDTH_PIX/width;

    CGFloat heightFactor = MAX_IMAGE_HEIGHT_PIX/height;

    CGFloat scaleFactor = 0.0;

    if (widthFactor > heightFactor) {

        scaleFactor = heightFactor; //scale to fit height

    }

    else{

        scaleFactor = widthFactor; //scale to fit width

    }

    CGFloat scaledWidth = width * scaleFactor;

    CGFloat scaledHeight = height * scaleFactor;

    CGSize targetSize = CGSizeMake(scaledWidth, scaledHeight);

    

    UIGraphicsBeginImageContext(targetSize);//this wil crop

    

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.size.width = scaledWidth;

    thumbnailRect.size.height = scaledHeight;

    

    [self drawInRect:thumbnailRect];

    

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    

    //pop the context to get back to the default

    UIGraphicsEndImageContext();

    return newImage;

}

- (NSData *)imageData{

    return UIImageJPEGRepresentation(self, 1);

}

对了,图片的压缩一般多用于上传图片,所以要将图片转换成NSData 

原文地址:https://www.cnblogs.com/zhouyantongiOSDev/p/4371437.html