1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #import "WYImageScaleTool.h" @implementation WYImageScaleTool
+ (instancetype)sharedManager { static WYImageScaleTool *_instace =nil; static dispatch_once_tonceToken; dispatch_once(&onceToken, ^{ _instace = [[WYImageScaleTool alloc] init]; }); return _instace; }
+ (NSData*)compressOfImageWithWeiChat:(UIImage*)source_image maxSize:(NSInteger)maxSize { CGFloat compression = 1.0f; CGFloat minCompression = 0.5f; NSData *imageData = UIImageJPEGRepresentation(source_image, compression); CGFloat imageFileSize = imageData.length/1024; NSLog(@"原图大小 = %lu Kb", (unsignedlong)imageData.length/1024);
WYImageScaleTool *tool = [WYImageScaleTool sharedManager]; UIImage *newImage = [tool Compresimage:source_image];
// 每次减少的比例 float scale =0.05; // 循环条件:没到最小压缩比例,且没压缩到目标大小 while((compression > minCompression) && (imageFileSize > maxSize)) { compression -= scale; imageData =UIImageJPEGRepresentation(newImage, compression);
// NSLog(@"\n压缩比 -> %g, \n压缩后的大小 -> %lu Kb, \n缩放后的大小 -> %lu Kb, \n原图大小 -> %lu Kb", compression, (unsigned long)imageData.length/1024, (unsigned long)scaleData.length/1024, (unsigned long)originalData.length/1024); }
NSLog(@"压缩后图片大小 = %lu Kb", (unsigned long)imageData.length/1024); return imageData; }
- (UIImage*)Compresimage:(UIImage*)image { CGSize size = [self CompressSizeImage:image]; UIImage *reImage = [self resizedImage:sizeimage:image]; return reImage; }
- (CGSize)CompressSizeImage:(UIImage*)image { CGFloat width = image.size.width; CGFloat height = image.size.height; CGFloat boundary =1280; if(width < boundary && height < boundary) { return CGSizeMake(width, height); }
CGFloat ratio =MAX(width, height) /MIN(width, height); if(ratio <=2) { CGFloat x =MAX(width, height) / boundary; if(width > height) { width = boundary; height = height / x; }else{ height = boundary; width = width / x; }
}else{
if(MIN(width, height) >= boundary) { CGFloat x =MIN(width, height) / boundary; if(width < height) { width = boundary; height = height / x; }else{ height = boundary; width = width / x; } }
} return CGSizeMake(width, height); }
- (UIImage*)resizedImage:(CGSize)newSize image:(UIImage*)image { CGRect newRect =CGRectMake(0,0, newSize.width, newSize.height); UIGraphicsBeginImageContext(newRect.size); UIImage *newImage = [[UIImage alloc] initWithCGImage:image.CGImagescale:1 orientation:image.imageOrientation]; [newImage drawInRect:newRect]; newImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
@end
|