压缩图片,如果图片大于100kb,就循环压缩

// 压缩图片,如果图片大于100kb,就循环压缩
+ (NSData *)compressionWithImage:(UIImage *)image{
   
    // 先按宽度压缩
    UIImage *newImage = [image resizeImageGreaterThan:480];
   
    NSData *data;
    float quality = 1.0f;
    if (UIImageJPEGRepresentation(newImage, quality)) {
        data = UIImageJPEGRepresentation(newImage, quality);
        while (data.length / 1024.0f > 100 && quality > 0.5) {
            quality -= 0.1f;
            data = UIImageJPEGRepresentation(newImage, quality);
        }
    }
   
    if (data == nil) {
        data = UIImageJPEGRepresentation(newImage, 0.5);
    }
   
    return data;
}


----mark
// 这里是UIImage的一个扩展,按宽度压缩
#import "UIImage+Resize.h"

@implementation UIImage (Resize)

- (UIImage*)resizeImageGreaterThan:(CGFloat)maxL {
    UIImage * res;
    UIImage * img = self;
    res = img;
    float height = img.size.height;
    float width = img.size.width;
    float bigger = height > width ? height : width;
    float coefficient = 1.0;
    int maxPix = maxL;
    if (bigger > maxPix) {
        coefficient = maxPix / bigger;
        res = [img resizeImageWithNewSize:CGSizeMake(width * coefficient, height * coefficient)];
    }
    return res;
}

- (UIImage*)resizeImageWithNewSize:(CGSize)newSize
{
CGFloat newWidth = newSize.width;
CGFloat newHeight = newSize.height;
    // Resize image if needed.
    float width  = self.size.width;
    float height = self.size.height;
    // fail safe
    if (width == 0 || height == 0)
return self;
   
    //float scale;

    if (width != newWidth || height != newHeight) {
        UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
        [self drawInRect:CGRectMake(0, 0, newWidth, newHeight)];

        UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //NSData *jpeg = UIImageJPEGRepresentation(image, 0.8);
        return resized;
    }
    return self;
}


@end



#import <UIKit/UIKit.h>

@interface UIImage (Resize)

/*
* brife 缩放图片
* maxL  图片的高度
*/
- (UIImage*)resizeImageGreaterThan:(CGFloat)maxL;
@end

你可能感兴趣的:(压缩)