ios 头像上传前的头像处理

一,图片的压缩,按照比例压缩

+ (UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{

    // 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了(非常重要,否则就会失真)
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();


    return scaledImage;
}

二,图片上传服务器

#import "AdjustUpImageSize.h"
#define MAX_SIZEKB 1024.0
@implementation AdjustUpImageSize

// sourceImage 是上面方法里处理过的图片
+ (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize{

    if (maxSize <= 0.0) maxSize = MAX_SIZEKB;
    if (maxImageSize <= 0.0) maxImageSize = MAX_SIZEKB;

    //先调整分辨率
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);

    CGFloat tempHeight = newSize.height / maxImageSize;
    CGFloat tempWidth = newSize.width / maxImageSize;

    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }

    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(sourceImage,1.0);
    CGFloat sizeOriginKB = imageData.length / MAX_SIZEKB;

    CGFloat resizeRate = 0.9;
    while (sizeOriginKB > maxSize && resizeRate > 0.1) {
        imageData = UIImageJPEGRepresentation(sourceImage,resizeRate);
        sizeOriginKB = imageData.length / MAX_SIZEKB;
        resizeRate -= 0.1;
    }

    return imageData;
}
@end

没有更多推荐了,返回首页