// // UIImage+Scale.m // Meet // // Created by yuqingyuan on 2018/9/28. // Copyright © 2018年 ko1o. All rights reserved. // #import "UIImage+Scale.h" @implementation UIImage (Scale) + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size { if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]); } else { UIGraphicsBeginImageContext(size); } [image drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } + (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height { CGSize newSize = [self sizeWithImageSize:image.size scaledToMaxWidth:width maxHeight:height]; return [self imageWithImage:image scaledToSize:newSize]; } + (CGSize)sizeWithImageSize:(CGSize)size scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height { CGFloat oldWidth = size.width; CGFloat oldHeight = size.height; CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight; CGFloat newHeight = oldHeight * scaleFactor; CGFloat newWidth = oldWidth * scaleFactor; CGSize newSize = CGSizeMake(newWidth, newHeight); return newSize; } NSData *comprossImageToSize(UIImage *image, int size) { int maxLength = size; // 最大500k //首先判断原图大小是否在要求内,如果满足要求则不进行压缩,over CGFloat compression = 1; NSData *data = UIImageJPEGRepresentation(image, compression); if (data.length < maxLength) return UIImageJPEGRepresentation(image, 1.0); //原图大小超过范围,先进行“压处理”,这里 压缩比 采用二分法进行处理,6次二分后的最小压缩比是0.015625,已经够小了 CGFloat max = 1; CGFloat min = 0; for (int i = 0; i < 6; ++i) { compression = (max + min) / 2; data = UIImageJPEGRepresentation(image, compression); if (data.length < maxLength * 0.9) { min = compression; } else if (data.length > maxLength) { max = compression; } else { break; } } //判断“压处理”的结果是否符合要求,符合要求就over UIImage *resultImage = [UIImage imageWithData:data]; if (data.length < maxLength) return data; //缩处理,直接用大小的比例作为缩处理的比例进行处理,因为有取整处理,所以一般是需要两次处理 NSUInteger lastDataLength = 0; while (data.length > maxLength && data.length != lastDataLength) { lastDataLength = data.length; //获取处理后的尺寸 CGFloat ratio = (CGFloat)maxLength / data.length; CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); //通过图片上下文进行处理图片 UIGraphicsBeginImageContext(size); [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //获取处理后图片的大小 data = UIImageJPEGRepresentation(resultImage, compression); } return data; } NSData *compressImageToDataIfNeed(UIImage *image) { return comprossImageToSize(image, 500 * 1000); } UIImage *compressImageToSizeIfNeed(UIImage *image, int size) { NSData *data = comprossImageToSize(image, size); return [[UIImage alloc] initWithData:data]; } @end