forked from IcaliaLabs/UIImage-ImageCompress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIImage+ImageCompress.m
86 lines (65 loc) · 2.74 KB
/
UIImage+ImageCompress.m
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
//
// UIImage+ImageCompress.m
// UIIImageCompressExample
//
// Created by Abraham Kuri on 12/12/13.
// Copyright (c) 2013 Icalia Labs. All rights reserved.
//
#import "UIImage+ImageCompress.h"
@implementation UIImage (ImageCompress)
+ (UIImage *)compressImage:(UIImage *)image
compressRatio:(CGFloat)ratio
{
return [[self class] compressImage:image compressRatio:ratio maxCompressRatio:0.1f];
}
+ (UIImage *)compressImage:(UIImage *)image compressRatio:(CGFloat)ratio maxCompressRatio:(CGFloat)maxRatio
{
//We define the max and min resolutions to shrink to
int MIN_UPLOAD_RESOLUTION = 1136 * 640;
int MAX_UPLOAD_SIZE = 50;
float factor;
float currentResolution = image.size.height * image.size.width;
//We first shrink the image a little bit in order to compress it a little bit more
if (currentResolution > MIN_UPLOAD_RESOLUTION) {
factor = sqrt(currentResolution / MIN_UPLOAD_RESOLUTION) * 2;
image = [self scaleDown:image withSize:CGSizeMake(image.size.width / factor, image.size.height / factor)];
}
//Compression settings
CGFloat compression = ratio;
CGFloat maxCompression = maxRatio;
//We loop into the image data to compress accordingly to the compression ratio
NSData *imageData = UIImageJPEGRepresentation(image, compression);
while ([imageData length] > MAX_UPLOAD_SIZE && compression > maxCompression) {
compression -= 0.10;
imageData = UIImageJPEGRepresentation(image, compression);
}
//Retuns the compressed image
return [[UIImage alloc] initWithData:imageData];
}
+ (UIImage *)compressRemoteImage:(NSString *)url
compressRatio:(CGFloat)ratio
maxCompressRatio:(CGFloat)maxRatio
{
//Parse the URL
NSURL *imageURL = [NSURL URLWithString:url];
//We init the image with the rmeote data
UIImage *remoteImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
//Returns the remote image compressed
return [[self class] compressImage:remoteImage compressRatio:ratio maxCompressRatio:maxRatio];
}
+ (UIImage *)compressRemoteImage:(NSString *)url compressRatio:(CGFloat)ratio
{
return [[self class] compressRemoteImage:url compressRatio:ratio maxCompressRatio:0.1f];
}
+ (UIImage*)scaleDown:(UIImage*)image withSize:(CGSize)newSize
{
//We prepare a bitmap with the new size
UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
//Draws a rect for the image
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
//We set the scaled image from the context
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end