-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathImageHelper.m
371 lines (323 loc) · 10.5 KB
/
ImageHelper.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#import "ImageHelper.h"
@implementation ImageHelper
+(UIImage*) imageFromDictionary:(NSDictionary*)dictionary {
return dictionary[@"UIImagePickerControllerOriginalImage"];
}
+(NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"jpg";
case 0x89:
return @"png";
default:
return nil;
}
}
+(NSString*)imageFromDataSync:(NSData*)data {
@try {
NSString* extension = [self contentTypeForImageData:data];
if(extension==nil)
[NSException raise:@"InvalidImageFormat" format:@"Invalid image format"];
UIImage* newImage = [UIImage imageWithData:data];
NSString* path = [self createImagePathWithExtension:extension temp:YES];
[self saveImage:newImage path:path];
return path;
}
@catch (NSException* e) {
return nil;
}
}
+(void)imageFromData:(NSData*)data onComplete:(StringAction)onComplete onFail:(StringAction)onFail
{
@try {
NSString* extension = [self contentTypeForImageData:data];
if(extension==nil)
[NSException raise:@"InvalidImageFormat" format:@"Invalid image format"];
UIImage* newImage = [UIImage imageWithData:data];
NSString* path = [self createImagePathWithExtension:extension temp:YES];
[self saveImage:newImage path:path];
onComplete(path);
}
@catch (NSException* e) {
onFail([NSString stringWithFormat:@"Image load error: %@", e]);
}
}
+(void)saveImage:(UIImage*)image path:(NSString*)path
{
@autoreleasepool {
NSData* imageData;
NSString* ext = [[path pathExtension] lowercaseString];
if([ext isEqualToString:@"png"]) {
imageData = UIImagePNGRepresentation(image);
} else {
imageData = UIImageJPEGRepresentation(image, 0.9f);
}
[imageData writeToFile:path atomically:NO];
}
}
+(NSArray*) getImageSize:(NSString*)path {
CGFloat width = 0.0f, height = 0.0f;
NSURL *imageFileURL = [NSURL fileURLWithPath:path];
CFURLRef url = (__bridge CFURLRef) imageFileURL;
CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, nil);
if (imageSource == nil) {
return @[ @( 0 ), @( 0 )];
}
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil);
CFRelease(imageSource);
if (imageProperties != nil) {
CFNumberRef widthNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
if (widthNum != nil) {
CFNumberGetValue(widthNum, kCFNumberCGFloatType, &width);
}
CFNumberRef heightNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
if (heightNum != nil) {
CFNumberGetValue(heightNum, kCFNumberCGFloatType, &height);
}
CFRelease(imageProperties);
}
return @[ @( (int)width ), @( (int)height )]; //Weird spacing here to avoid uxl expansion issues
}
+(UIImage*) correctImageOrientation:(UIImage*)image {
if (image.imageOrientation == UIImageOrientationUp) return image;
CGAffineTransform transform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
transform = CGAffineTransformRotate(transform, (CGFloat) M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformRotate(transform, (CGFloat) M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, image.size.height);
transform = CGAffineTransformRotate(transform, (CGFloat) -M_PI_2);
break;
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
break;
}
switch (image.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, image.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationUp:
case UIImageOrientationDown:
case UIImageOrientationLeft:
case UIImageOrientationRight:
break;
}
CGContextRef ctx = CGBitmapContextCreate(nil, (size_t) image.size.width, (size_t) image.size.height,
CGImageGetBitsPerComponent(image.CGImage), 0,
CGImageGetColorSpace(image.CGImage),
CGImageGetBitmapInfo(image.CGImage));
CGContextConcatCTM(ctx, transform);
switch (image.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
break;
}
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
+(void)cropImage:(NSString*)path
desiredRect:(CGRect)rect
onComplete:(StringAction)onComplete
onFail:(StringAction)onFail
performInPlace:(BOOL)inPlace
{
@try
{
UIImage* newImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([[UIImage imageWithContentsOfFile:path] CGImage], rect)];
if(!inPlace)
path = [self createImagePath:YES];
[self saveImage:newImage path:path];
onComplete(path);
}
@catch (NSException* e)
{
onFail([NSString stringWithFormat:@"Image crop error: %@", e]);
}
}
+(void)resizeImage:(NSString*)path
width:(float)desiredWidth
height:(float)desiredHeight
mode:(int)mode
onComplete:(StringAction)onComplete
onFail:(StringAction)onFail
performInPlace:(BOOL)inPlace
{
@try {
UIImage* image = [UIImage imageWithContentsOfFile:path];
CGSize currentSize = [image size];
float width = currentSize.width;
float height = currentSize.height;
float ratio;
UIImage *newImage = nil;
CGRect cropRect;
if (width > desiredWidth || height > desiredHeight)
{
switch(mode){
case 1:
//Keep aspect
if (width > desiredWidth) {
ratio = desiredWidth / width;
width *= ratio;
height *= ratio;
}
if (height > desiredHeight) {
ratio = desiredHeight / height;
width *= ratio;
height *= ratio;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width,height), NO, 1.0);
[image drawInRect:CGRectMake(0, 0, width, height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
break;
case 2:
//resize to closest with aspect correction, then crop with centered rect
if (width > height) {
if (height > desiredHeight)
{
ratio = desiredHeight / height;
width *= ratio;
height *= ratio;
}else if (width > desiredWidth)
{
ratio = desiredWidth / width;
width *= ratio;
height *= ratio;
}
} else {
if (width > desiredWidth)
{
ratio = desiredWidth / width;
width *= ratio;
height *= ratio;
}
else if (height > desiredHeight)
{
ratio = desiredHeight / height;
width *= ratio;
height *= ratio;
}
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width,height), NO, 1.0);
[image drawInRect:CGRectMake(0, 0, width, height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cropRect = CGRectMake(
MAX(0, width/2 - desiredWidth/2),
MAX(0, height/2 - desiredHeight/2),
MIN(desiredWidth, width),
MIN(desiredHeight, height));
@autoreleasepool {
struct CGImage* cgimage = CGImageCreateWithImageInRect([newImage CGImage], cropRect);
newImage = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);
}
break;
default:
//Use width/height as given
UIGraphicsBeginImageContextWithOptions(CGSizeMake(desiredWidth, desiredHeight), NO, 1.0);
[image drawInRect:CGRectMake(0, 0, desiredWidth, desiredHeight)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
//Save the final image
if(!inPlace)
path = [self createImagePath:YES];
[self saveImage:newImage path:path];
onComplete(path);
}else
{
//No resizing necessary
onComplete(path);
}
}@catch (NSException * e){
onFail([NSString stringWithFormat:@"Image resize error: %@", e]);
}
}
+(void) imageFromBase64String:(NSString*)b64
onComplete:(StringAction)a
onFail:(StringAction)b
{
@try {
NSData* data = [[NSData alloc] initWithBase64EncodedString:b64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage* image = [UIImage imageWithData:data];
NSString* path = [self createImagePathWithExtension:@"png" temp:YES];
[self saveImage:image path:path];
a(path);
} @catch(NSException* e) {
b(@"Could not decode image");
}
}
+(void) base64FromImageAtPath:(NSString*)path
onComplete:(StringAction)a
onFail:(StringAction)b
{
UIImage* img = [UIImage imageWithContentsOfFile:path];
@try {
NSString* b64 = [UIImageJPEGRepresentation(img, 0.9f) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
a(b64);
}@catch(NSException* e){
b(@"Could not encode image");
}
}
+(NSString*) createImagePath:(BOOL)temp
{
NSString* p = [NSString stringWithFormat:@"%@images", temp?[self applicationTempDirectory]:[self applicationDocumentsDirectory]];
NSError * error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:p withIntermediateDirectories:YES attributes:nil error:&error];
if (error != nil) {
NSLog(@"error creating directory: %@", error);
}
return p;
}
+(NSString*) createImagePathWithExtension:(NSString*)extension
temp:(BOOL)temp
{
NSString *uuid = [[NSUUID UUID] UUIDString];
return [NSString stringWithFormat:@"%@/IMG_%@.%@", [self createImagePath:temp], uuid, extension];
}
+(NSString*) localPathFromPHImageFileURL:(NSURL*)url
temp:(BOOL)temp
{
NSString* name = [[url path] lastPathComponent];
NSString* uuid = [[NSUUID UUID] UUIDString];
return [NSString stringWithFormat:@"%@/%@%@", [self createImagePath:temp], uuid, name];
}
+(NSString*) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}
+(NSString*) applicationTempDirectory {
return NSTemporaryDirectory();
}
@end