iOS 图片压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface UIImage (ZDCompress)

/**
将图片压缩到指定宽度,保持原来图片的宽高比

@param width 图片宽度
@return image
*/
- (UIImage *)zd_compressToWidth:(CGFloat)width;

/**
将图片在子线程中压缩,block在主线程回调,保证压缩到指定大小,尽量减少失真

@param length 大小,100K就是100*1024
@param block 完成回调
*/
- (void)zd_compressToDataLength:(NSInteger)length block:(void(^)(NSData *data))block;

@end
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;
}
}
});
}


iOS 图片压缩
http://example.com/2017/12/10/iOS-图片压缩/
作者
guanzhendong
发布于
2017年12月10日
许可协议