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
| - (UIImage *)zd_compressToWidth:(CGFloat)width { if (width <= 0 || [self isKindOfClass:[NSNull class]]) return nil; if (width >= self.size.width) return self; CGSize newSize = CGSizeMake(width, width * (self.size.height / self.size.width)); UIGraphicsBeginImageContext(newSize); [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
- (void)zd_compressToDataLength:(NSInteger)length block:(void(^)(NSData *data))block { if (length <= 0 || [self isKindOfClass:[NSNull class]]) return; NSData *originalData = UIImagePNGRepresentation(self); if (length >= originalData.length) { block(originalData); return; } dispatch_async(dispatch_get_global_queue(0, 0), ^{ UIImage *newImage = [self copy]; NSData *data = UIImageJPEGRepresentation(newImage, 1.0); if (data.length / 1024 < 1024) { NSLog(@"图片压缩前的大小:%luKB", data.length / 1024); } else { NSLog(@"图片压缩前的大小:%.2fMB", (float)data.length / 1024 / 1024); } NSLog(@"------------------图片开始压缩------------------"); CGFloat scale = 0.9; NSData *jpgData = UIImageJPEGRepresentation(newImage, scale); while (jpgData.length > length) { newImage = [newImage zd_compressToWidth:newImage.size.width * scale]; NSData *newImageData = UIImageJPEGRepresentation(newImage, 0.0); if (newImageData.length < length) { newImageData = UIImageJPEGRepresentation(newImage, scale); while (newImageData.length > length) { scale -= 0.1; if (scale < 0) break; newImageData = UIImageJPEGRepresentation(newImage, scale); } dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"------------------图片完成压缩------------------"); NSLog(@"图片压缩后的大小:%luKB", newImageData.length / 1024); block(newImageData); }); return; } } }); }
|