react-native-compressor 1.7.2 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +51 -8
  2. package/android/build.gradle +9 -0
  3. package/android/src/main/java/com/reactnativecompressor/Audio/AudioCompressor.kt +527 -0
  4. package/android/src/main/java/com/reactnativecompressor/Audio/AudioMain.kt +31 -0
  5. package/android/src/main/java/com/reactnativecompressor/CompressorModule.kt +169 -0
  6. package/android/src/main/java/com/reactnativecompressor/CompressorPackage.kt +34 -0
  7. package/android/src/main/java/com/reactnativecompressor/Image/ImageCompressor.kt +199 -0
  8. package/android/src/main/java/com/reactnativecompressor/Image/ImageCompressorOptions.kt +57 -0
  9. package/android/src/main/java/com/reactnativecompressor/Image/ImageMain.kt +31 -0
  10. package/android/src/main/java/com/reactnativecompressor/Image/ImageSize.kt +3 -0
  11. package/android/src/main/java/com/reactnativecompressor/Utils/Downloader.kt +119 -0
  12. package/android/src/main/java/com/reactnativecompressor/Utils/EventEmitterHandler.kt +66 -0
  13. package/android/src/main/java/com/reactnativecompressor/Utils/MediaCache.kt +61 -0
  14. package/android/src/main/java/com/reactnativecompressor/Utils/RealPathUtil.kt +177 -0
  15. package/android/src/main/java/com/reactnativecompressor/Utils/Uploader.kt +117 -0
  16. package/android/src/main/java/com/reactnativecompressor/Utils/Utils.kt +162 -0
  17. package/android/src/main/java/com/reactnativecompressor/Utils/createVideoThumbnail.kt +158 -0
  18. package/android/src/main/java/com/reactnativecompressor/Video/AutoVideoCompression.kt +63 -0
  19. package/android/src/main/java/com/reactnativecompressor/Video/VideoCompressorHelper.kt +125 -0
  20. package/android/src/main/java/com/reactnativecompressor/Video/VideoMain.kt +86 -0
  21. package/android/src/newarch/CompressorSpec.kt +5 -0
  22. package/android/src/oldarch/CompressorSpec.kt +34 -0
  23. package/ios/Audio/AudioMain.swift +115 -0
  24. package/ios/Compressor-Bridging-Header.h +1 -2
  25. package/ios/Compressor.h +0 -8
  26. package/ios/Compressor.mm +37 -389
  27. package/ios/CompressorManager.swift +107 -0
  28. package/ios/Image/ImageCompressor.swift +354 -0
  29. package/ios/Image/ImageCompressorOptions.swift +93 -0
  30. package/ios/Image/ImageMain.swift +27 -0
  31. package/ios/Utils/CreateVideoThumbnail.swift +111 -0
  32. package/ios/Utils/Downloader.swift +157 -0
  33. package/ios/Utils/EventEmitterHandler.swift +54 -0
  34. package/ios/Utils/MediaCache.swift +48 -0
  35. package/ios/Utils/Uploader.swift +99 -0
  36. package/ios/Utils/Utils.swift +110 -0
  37. package/ios/Video/{VideoCompressor.swift → VideoMain.swift} +167 -146
  38. package/lib/commonjs/Image/index.js +1 -1
  39. package/lib/commonjs/Image/index.js.map +1 -1
  40. package/lib/commonjs/Main.js +1 -8
  41. package/lib/commonjs/Main.js.map +1 -1
  42. package/lib/commonjs/Spec/NativeCompressor.js.map +1 -1
  43. package/lib/commonjs/Video/index.js +4 -33
  44. package/lib/commonjs/Video/index.js.map +1 -1
  45. package/lib/commonjs/expo-plugin/compressor.js.map +1 -1
  46. package/lib/commonjs/index.js +25 -6
  47. package/lib/commonjs/index.js.map +1 -1
  48. package/lib/commonjs/utils/Downloader.js +38 -0
  49. package/lib/commonjs/utils/Downloader.js.map +1 -0
  50. package/lib/commonjs/utils/Uploader.js +40 -0
  51. package/lib/commonjs/utils/Uploader.js.map +1 -0
  52. package/lib/commonjs/utils/index.js +47 -1
  53. package/lib/commonjs/utils/index.js.map +1 -1
  54. package/lib/module/Image/index.js +1 -1
  55. package/lib/module/Image/index.js.map +1 -1
  56. package/lib/module/Main.js +1 -7
  57. package/lib/module/Main.js.map +1 -1
  58. package/lib/module/Spec/NativeCompressor.js.map +1 -1
  59. package/lib/module/Video/index.js +5 -33
  60. package/lib/module/Video/index.js.map +1 -1
  61. package/lib/module/expo-plugin/compressor.js.map +1 -1
  62. package/lib/module/index.js +9 -7
  63. package/lib/module/index.js.map +1 -1
  64. package/lib/module/utils/Downloader.js +31 -0
  65. package/lib/module/utils/Downloader.js.map +1 -0
  66. package/lib/module/utils/Uploader.js +33 -0
  67. package/lib/module/utils/Uploader.js.map +1 -0
  68. package/lib/module/utils/index.js +9 -0
  69. package/lib/module/utils/index.js.map +1 -1
  70. package/lib/typescript/Image/index.d.ts +4 -0
  71. package/lib/typescript/Image/index.d.ts.map +1 -1
  72. package/lib/typescript/Main.d.ts +1 -2
  73. package/lib/typescript/Main.d.ts.map +1 -1
  74. package/lib/typescript/Spec/NativeCompressor.d.ts +16 -2
  75. package/lib/typescript/Spec/NativeCompressor.d.ts.map +1 -1
  76. package/lib/typescript/Video/index.d.ts +4 -28
  77. package/lib/typescript/Video/index.d.ts.map +1 -1
  78. package/lib/typescript/index.d.ts +7 -4
  79. package/lib/typescript/index.d.ts.map +1 -1
  80. package/lib/typescript/utils/Downloader.d.ts +2 -0
  81. package/lib/typescript/utils/Downloader.d.ts.map +1 -0
  82. package/lib/typescript/utils/Uploader.d.ts +28 -0
  83. package/lib/typescript/utils/Uploader.d.ts.map +1 -0
  84. package/lib/typescript/utils/index.d.ts +4 -1
  85. package/lib/typescript/utils/index.d.ts.map +1 -1
  86. package/package.json +6 -4
  87. package/src/Image/index.tsx +5 -1
  88. package/src/Main.tsx +1 -15
  89. package/src/Spec/NativeCompressor.ts +25 -2
  90. package/src/Video/index.tsx +11 -84
  91. package/src/expo-plugin/compressor.ts +1 -1
  92. package/src/index.tsx +12 -3
  93. package/src/utils/Downloader.tsx +38 -0
  94. package/src/utils/Uploader.tsx +78 -0
  95. package/src/utils/index.tsx +15 -0
  96. package/android/src/main/java/com/reactnativecompressor/Audio/AudioCompressor.java +0 -605
  97. package/android/src/main/java/com/reactnativecompressor/CompressorModule.java +0 -220
  98. package/android/src/main/java/com/reactnativecompressor/CompressorPackage.java +0 -58
  99. package/android/src/main/java/com/reactnativecompressor/Image/ImageCompressor.java +0 -257
  100. package/android/src/main/java/com/reactnativecompressor/Image/utils/ImageCompressorOptions.java +0 -69
  101. package/android/src/main/java/com/reactnativecompressor/Image/utils/ImageSize.java +0 -13
  102. package/android/src/main/java/com/reactnativecompressor/Utils/FileUplaoder/FileUploadHelper.java +0 -39
  103. package/android/src/main/java/com/reactnativecompressor/Utils/FileUplaoder/FileUploader.java +0 -129
  104. package/android/src/main/java/com/reactnativecompressor/Utils/MediaCache.java +0 -65
  105. package/android/src/main/java/com/reactnativecompressor/Utils/RealPathUtil.java +0 -210
  106. package/android/src/main/java/com/reactnativecompressor/Utils/Utils.java +0 -272
  107. package/android/src/main/java/com/reactnativecompressor/Video/AutoVideoCompression/AutoVideoCompression.java +0 -87
  108. package/android/src/main/java/com/reactnativecompressor/Video/VideoCompressorHelper.java +0 -182
  109. package/android/src/main/java/com/reactnativecompressor/Video/VideoModule.java +0 -112
  110. package/android/src/newarch/CompressorSpec.java +0 -9
  111. package/android/src/newarch/VideoCompressorSpec.java +0 -9
  112. package/android/src/oldarch/CompressorSpec.java +0 -34
  113. package/android/src/oldarch/VideoCompressorSpec.java +0 -26
  114. package/ios/Image/ImageCompressor.h +0 -22
  115. package/ios/Image/ImageCompressor.m +0 -540
  116. package/ios/Image/ImageCompressorOptions.h +0 -28
  117. package/ios/Image/ImageCompressorOptions.m +0 -97
  118. package/ios/Utils/Downloader.h +0 -16
  119. package/ios/Utils/Downloader.m +0 -150
  120. package/ios/Utils/MediaCache.h +0 -11
  121. package/ios/Utils/MediaCache.m +0 -51
  122. package/ios/Video/VideoCompressor.h +0 -5
  123. package/ios/Video/VideoCompressor.m +0 -1
  124. package/lib/commonjs/Spec/NativeVideoCompressor.js +0 -10
  125. package/lib/commonjs/Spec/NativeVideoCompressor.js.map +0 -1
  126. package/lib/module/Spec/NativeVideoCompressor.js +0 -3
  127. package/lib/module/Spec/NativeVideoCompressor.js.map +0 -1
  128. package/lib/typescript/Spec/NativeVideoCompressor.d.ts +0 -13
  129. package/lib/typescript/Spec/NativeVideoCompressor.d.ts.map +0 -1
  130. package/src/Spec/NativeVideoCompressor.ts +0 -14
@@ -1,540 +0,0 @@
1
- #import <Accelerate/Accelerate.h>
2
- #import <CoreGraphics/CoreGraphics.h>
3
- #import <Photos/Photos.h>
4
- #import <React/RCTUtils.h>
5
- #import <React/RCTImageLoader.h>
6
- #import "ImageCompressor.h"
7
- #import <React/RCTConvert.h>
8
- #import <Foundation/Foundation.h>
9
- #import <MobileCoreServices/MobileCoreServices.h>
10
- #import <React/RCTEventEmitter.h>
11
- #import "../Utils/Downloader.h"
12
- #import "react_native_compressor-Swift.h"
13
- #import "VideoCompressor.h"
14
- #import "MediaCache.h"
15
-
16
- @implementation ImageCompressor
17
- Compressor *sharedCompressorObject;
18
- id sharedVideoCompressorObject;
19
-
20
- + (void)initCompressorInstance:(Compressor*)instance {
21
- sharedCompressorObject=instance;
22
- }
23
-
24
- + (void)initVideoCompressorInstance:(id)object {
25
- sharedVideoCompressorObject=object;
26
- }
27
-
28
- + (CGSize) findTargetSize: (UIImage *) image maxWidth: (int) maxWidth maxHeight: (int) maxHeight {
29
- CGFloat width = image.size.width;
30
- CGFloat height = image.size.height;
31
-
32
- if (width > height) {
33
- CGFloat newHeight = height / (width / maxWidth);
34
- return CGSizeMake(maxWidth, newHeight);
35
- }
36
-
37
- CGFloat newWidth = width / (height / maxHeight);
38
- return CGSizeMake(newWidth, maxHeight);
39
- }
40
-
41
- +(UIImage *) decodeImage: (NSString *) value {
42
- NSData *data = [[NSData alloc] initWithBase64EncodedString:value options: NSDataBase64DecodingIgnoreUnknownCharacters];
43
- return [[UIImage alloc] initWithData:data];
44
- }
45
-
46
- +(UIImage *) loadImage:(NSString *)path {
47
- UIImage *image=nil;
48
- if ([path hasPrefix:@"data:"] || [path hasPrefix:@"file:"]) {
49
- NSURL *imageUrl = [[NSURL alloc] initWithString:path];
50
- image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
51
- } else {
52
- image = [[UIImage alloc] initWithContentsOfFile:path];
53
- }
54
- return image;
55
- }
56
-
57
-
58
- +(UIImage *)manualResize:(UIImage *)image maxWidth:(int)maxWidth maxHeight:(int)maxHeight {
59
- CGSize targetSize = [self findTargetSize:image maxWidth:maxWidth maxHeight:maxHeight];
60
-
61
- CGImageRef cgImage = image.CGImage;
62
-
63
- int sourceWidth = image.size.width;
64
- int sourceHeight = image.size.height;
65
- int targetWidth = targetSize.width;
66
- int targetHeight = targetSize.height;
67
- int bytesPerPixel = 4;
68
- int sourceBytesPerRow = sourceWidth * bytesPerPixel;
69
- int targetBytesPerRow = targetWidth * bytesPerPixel;
70
- int bitsPerComponent = 8;
71
-
72
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
73
-
74
- unsigned char *sourceData = (unsigned char*)calloc(sourceHeight * sourceWidth * bytesPerPixel, sizeof(unsigned char));
75
-
76
- CGContextRef context = CGBitmapContextCreate(sourceData, sourceWidth, sourceHeight,
77
- bitsPerComponent, sourceBytesPerRow, colorSpace,
78
- kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
79
- CGContextDrawImage(context, CGRectMake(0, 0, sourceWidth, sourceHeight), cgImage);
80
- CGContextRelease(context);
81
-
82
- unsigned char *targetData = (unsigned char*)calloc(targetWidth * targetHeight * bytesPerPixel, sizeof(unsigned char));
83
-
84
- vImage_Buffer srcBuffer = {
85
- .data = sourceData,
86
- .width = sourceWidth,
87
- .height = sourceHeight,
88
- .rowBytes = sourceBytesPerRow
89
- };
90
- vImage_Buffer targetBuffer = {
91
- .data = targetData,
92
- .width = targetWidth,
93
- .height = targetHeight,
94
- .rowBytes = targetBytesPerRow
95
- };
96
-
97
- vImage_Error error = vImageScale_ARGB8888(&srcBuffer, &targetBuffer, nil, kvImageHighQualityResampling);
98
- free(sourceData);
99
- if (error != kvImageNoError) {
100
- free(targetData);
101
- NSException *exception = [[NSException alloc] initWithName: @"drawing_erro" reason:@"Problem while rendering your image" userInfo:nil];
102
- @throw exception;
103
- }
104
-
105
- CGContextRef targetContext = CGBitmapContextCreate(targetData, targetWidth, targetHeight,
106
- bitsPerComponent, targetBytesPerRow, colorSpace,
107
- kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
108
- CGImageRef targetRef = CGBitmapContextCreateImage(targetContext);
109
-
110
- UIImage* resizedImage = [UIImage imageWithCGImage:targetRef];
111
-
112
- CGImageRelease(targetRef);
113
- CGColorSpaceRelease(colorSpace);
114
- CGContextRelease(targetContext);
115
-
116
-
117
- free(targetData);
118
-
119
- return resizedImage;
120
- }
121
-
122
- +(NSString *)manualCompress:(UIImage *)image output:(enum OutputType)output quality:(float)quality outputExtension:(NSString*)outputExtension isBase64:(Boolean)isBase64{
123
- NSData *data;
124
- NSException *exception;
125
-
126
- switch (output) {
127
- case jpg:
128
- data = UIImageJPEGRepresentation(image, quality);
129
- break;
130
- case png:
131
- data = UIImagePNGRepresentation(image);
132
- break;
133
- default:
134
- exception = [[NSException alloc] initWithName: @"unsupported_format" reason:@"This format is not supported." userInfo:nil];
135
- @throw exception;
136
- }
137
-
138
- if(isBase64)
139
- {
140
- return [data base64EncodedStringWithOptions:0];
141
- }
142
- else
143
- {
144
- NSString *filePath =[self generateCacheFilePath:outputExtension];
145
- [data writeToFile:filePath atomically:YES];
146
- NSString *returnablePath=[self makeValidUri:filePath];
147
- return returnablePath;
148
- }
149
- }
150
-
151
- + (NSString *)generateCacheFilePath:(NSString *)extension{
152
- NSUUID *uuid = [NSUUID UUID];
153
- NSString *imageNameWihtoutExtension = [uuid UUIDString];
154
- NSString *imageName=[imageNameWihtoutExtension stringByAppendingPathExtension:extension];
155
- NSString *filePath =
156
- [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
157
- return filePath;
158
- }
159
-
160
- +(UIImage *)scaleAndRotateImage:(UIImage *)image{
161
- // No-op if the orientation is already correct
162
- if (image.imageOrientation == UIImageOrientationUp) return image;
163
-
164
- // We need to calculate the proper transformation to make the image upright.
165
- // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
166
- CGAffineTransform transform = CGAffineTransformIdentity;
167
-
168
- switch (image.imageOrientation) {
169
- case UIImageOrientationDown:
170
- case UIImageOrientationDownMirrored:
171
- transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
172
- transform = CGAffineTransformRotate(transform, M_PI);
173
- break;
174
-
175
- case UIImageOrientationLeft:
176
- case UIImageOrientationLeftMirrored:
177
- transform = CGAffineTransformTranslate(transform, image.size.width, 0);
178
- transform = CGAffineTransformRotate(transform, M_PI_2);
179
- break;
180
-
181
- case UIImageOrientationRight:
182
- case UIImageOrientationRightMirrored:
183
- transform = CGAffineTransformTranslate(transform, 0, image.size.height);
184
- transform = CGAffineTransformRotate(transform, -M_PI_2);
185
- break;
186
- case UIImageOrientationUp:
187
- case UIImageOrientationUpMirrored:
188
- break;
189
- }
190
-
191
- switch (image.imageOrientation) {
192
- case UIImageOrientationUpMirrored:
193
- case UIImageOrientationDownMirrored:
194
- transform = CGAffineTransformTranslate(transform, image.size.width, 0);
195
- transform = CGAffineTransformScale(transform, -1, 1);
196
- break;
197
-
198
- case UIImageOrientationLeftMirrored:
199
- case UIImageOrientationRightMirrored:
200
- transform = CGAffineTransformTranslate(transform, image.size.height, 0);
201
- transform = CGAffineTransformScale(transform, -1, 1);
202
- break;
203
- case UIImageOrientationUp:
204
- case UIImageOrientationDown:
205
- case UIImageOrientationLeft:
206
- case UIImageOrientationRight:
207
- break;
208
- }
209
-
210
- // Now we draw the underlying CGImage into a new context, applying the transform
211
- // calculated above.
212
- CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
213
- CGImageGetBitsPerComponent(image.CGImage), 0,
214
- CGImageGetColorSpace(image.CGImage),
215
- CGImageGetBitmapInfo(image.CGImage));
216
- CGContextConcatCTM(ctx, transform);
217
- switch (image.imageOrientation) {
218
- case UIImageOrientationLeft:
219
- case UIImageOrientationLeftMirrored:
220
- case UIImageOrientationRight:
221
- case UIImageOrientationRightMirrored:
222
- // Grr...
223
- CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
224
- break;
225
-
226
- default:
227
- CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
228
- break;
229
- }
230
-
231
- // And now we just create a new UIImage from the drawing context
232
- CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
233
- UIImage *img = [UIImage imageWithCGImage:cgimg];
234
- CGContextRelease(ctx);
235
- CGImageRelease(cgimg);
236
- return img;
237
- }
238
-
239
- +(NSString *)makeValidUri:(NSString *)filePath{
240
- NSURL *fileWithUrl = [NSURL fileURLWithPath:filePath];
241
- NSURL *absoluteUrl = [fileWithUrl URLByDeletingLastPathComponent];
242
- NSString *fileUrl = [NSString stringWithFormat:@"file://%@/%@", [absoluteUrl path] , [fileWithUrl lastPathComponent]];
243
- return fileUrl;
244
- }
245
-
246
- +(NSString *)manualCompressHandler:(NSString *)imagePath options:(ImageCompressorOptions*)options{
247
- NSException *exception;
248
- UIImage *image;
249
- switch (options.input) {
250
- case base64:
251
- image = [ImageCompressor decodeImage: imagePath];
252
- break;
253
- case uri:
254
- image = [ImageCompressor loadImage: imagePath];
255
- break;
256
- default:
257
- exception = [[NSException alloc] initWithName: @"unsupported_value" reason:@"Unsupported value type.." userInfo:nil];
258
- @throw exception;
259
- }
260
- image=[ImageCompressor scaleAndRotateImage:image];
261
- NSString *outputExtension=[ImageCompressorOptions getOutputInString:options.output];
262
- UIImage *resizedImage = [ImageCompressor manualResize:image maxWidth:options.maxWidth maxHeight:options.maxHeight];
263
- Boolean isBase64=options.returnableOutputType ==rbase64;
264
- NSString *result = [ImageCompressor manualCompress:resizedImage output:options.output quality:options.quality outputExtension:outputExtension isBase64:isBase64];
265
- return result;
266
- }
267
-
268
- +(NSString *)autoCompressHandler:(NSString *)imagePath options:(ImageCompressorOptions*)options{
269
-
270
- NSException *exception;
271
- UIImage *image=[ImageCompressor loadImage: imagePath];;
272
- image=[ImageCompressor scaleAndRotateImage:image];
273
- NSString *outputExtension=[ImageCompressorOptions getOutputInString:options.output];
274
-
275
-
276
- float actualHeight = image.size.height;
277
- float actualWidth = image.size.width;
278
- float maxHeight = 1280.0;
279
- float maxWidth = 1280.0;
280
- float imgRatio = actualWidth/actualHeight;
281
- float maxRatio = maxWidth/maxHeight;
282
- float compressionQuality = 0.8;
283
-
284
- if (actualHeight > maxHeight || actualWidth > maxWidth) {
285
- if(imgRatio < maxRatio){
286
- imgRatio = maxHeight / actualHeight;
287
- actualWidth = imgRatio * actualWidth;
288
- actualHeight = maxHeight;
289
- }
290
- else if(imgRatio > maxRatio){
291
- imgRatio = maxWidth / actualWidth;
292
- actualHeight = imgRatio * actualHeight;
293
- actualWidth = maxWidth;
294
- }else{
295
- actualHeight = maxHeight;
296
- actualWidth = maxWidth;
297
- }
298
- }
299
-
300
- CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
301
- UIGraphicsBeginImageContext(rect.size);
302
- [image drawInRect:rect];
303
- UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
304
- NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
305
- UIGraphicsEndImageContext();
306
- NSString *filePath =[self generateCacheFilePath:outputExtension];
307
- [imageData writeToFile:filePath atomically:YES];
308
- NSString *returnablePath=[self makeValidUri:filePath];
309
- return returnablePath;
310
- }
311
-
312
-
313
- + (void)getFileSizeFromURL:(NSString *)urlString completion:(void (^)(NSNumber *fileSize, NSError *error))completion {
314
- NSURL *url = [NSURL URLWithString:urlString];
315
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
316
- [request setHTTPMethod:@"HEAD"];
317
-
318
- NSURLSession *session = [NSURLSession sharedSession];
319
- NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
320
- if (error) {
321
- if (completion) {
322
- completion(nil, error);
323
- }
324
- return;
325
- }
326
-
327
- if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
328
- NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
329
- long long contentLength = [httpResponse expectedContentLength];
330
- if (completion) {
331
- completion([NSNumber numberWithLongLong:contentLength], nil);
332
- }
333
- } else {
334
- if (completion) {
335
- completion(nil, [NSError errorWithDomain:@"FileDownloadError" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Invalid response."}]);
336
- }
337
- }
338
- }];
339
-
340
- [task resume];
341
- }
342
-
343
-
344
- + (void)sendProgressUpdate:(NSNumber*)progress uuid:(NSString *)uuid type:(NSString *)type {
345
- NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
346
- NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
347
- params[@"uuid"] = uuid;
348
- data[@"progress"] = progress;
349
- params[@"data"] = data;
350
-
351
- if(type==@"image")
352
- {
353
- [sharedCompressorObject sendEventWithName:@"downloadProgress" body:params];
354
- }
355
- else
356
- {
357
- [sharedVideoCompressorObject sendEventWithName:@"downloadProgress" body:params];
358
- }
359
-
360
- }
361
-
362
-
363
- + (void)downloadFileAndSaveToCache:(NSString *)fileUrl uuid:(NSString *)uuid type:(NSString *)type completion:(void (^)(NSString *downloadedPath))completion {
364
-
365
- Downloader *downloader = [[Downloader alloc] init];
366
- [downloader downloadFile:fileUrl downloadCompleteCallback:^(NSString *filePath) {
367
- [MediaCache addCompletedImagePath:filePath];
368
- NSLog(@"download completed file path: %@",filePath);
369
- completion(filePath);
370
- } progressCallback:^(NSNumber * progress) {
371
- [self sendProgressUpdate:progress uuid:uuid type:type];
372
-
373
- } errorCallback:^(NSError * error) {
374
- NSLog(@"error downloadFile",error);
375
- }];
376
- }
377
-
378
- +(void)getAbsoluteImagePath:(NSString *)imagePath uuid:(NSString *)uuid completionHandler:(void (^)(NSString *absoluteImagePath))completionHandler
379
- {
380
- if([imagePath hasPrefix:@"http://"]||[imagePath hasPrefix:@"https://"])
381
- {
382
- [ImageCompressor downloadFileAndSaveToCache:imagePath uuid:uuid type:@"image" completion:^(NSString *downloadedPath) {
383
- completionHandler(downloadedPath); // Pass the downloaded path to the completionHandler
384
- }];
385
- return;
386
-
387
- }
388
- else if (![imagePath containsString:@"ph://"]) {
389
- completionHandler(imagePath);
390
- return;
391
- }
392
- NSURL *imageURL = [NSURL URLWithString:[imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
393
- CGSize size = CGSizeZero;
394
- CGFloat scale = 1;
395
- RCTResizeMode resizeMode = RCTResizeModeContain;
396
- NSString *assetID = @"";
397
- PHFetchResult *results;
398
- if (!imageURL) {
399
- NSString *errorText = @"Cannot load a photo library asset with no URL";
400
- @throw([NSException exceptionWithName:errorText reason:errorText userInfo:nil]);
401
- } else if ([imageURL.scheme caseInsensitiveCompare:@"assets-library"] == NSOrderedSame) {
402
- assetID = [imageURL absoluteString];
403
- results = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
404
- } else {
405
- assetID = [imageURL.absoluteString substringFromIndex:@"ph://".length];
406
- results = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil];
407
- }
408
- if (results.count == 0) {
409
- NSString *errorText = [NSString stringWithFormat:@"Failed to fetch PHAsset with local identifier %@ with no error message.", assetID];
410
- @throw([NSException exceptionWithName:errorText reason:errorText userInfo:nil]);
411
- }
412
- PHAsset *asset = [results firstObject]; // <-- WE GOT THE ASSET
413
- PHImageRequestOptions *imageOptions = [PHImageRequestOptions new];
414
- imageOptions.networkAccessAllowed = YES;
415
- imageOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
416
-
417
- BOOL useMaximumSize = CGSizeEqualToSize(size, CGSizeZero);
418
- CGSize targetSize;
419
- if (useMaximumSize) {
420
- targetSize = PHImageManagerMaximumSize;
421
- imageOptions.resizeMode = PHImageRequestOptionsResizeModeNone;
422
- } else {
423
- targetSize = CGSizeApplyAffineTransform(size, CGAffineTransformMakeScale(scale, scale));
424
- imageOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
425
- }
426
-
427
- PHImageContentMode contentMode = PHImageContentModeAspectFill;
428
- if (resizeMode == RCTResizeModeContain) {
429
- contentMode = PHImageContentModeAspectFit;
430
- }
431
- [[PHImageManager defaultManager] requestImageForAsset:asset
432
- targetSize:targetSize
433
- contentMode:contentMode
434
- options:imageOptions
435
- resultHandler:^(UIImage *result, NSDictionary<NSString *, id> *info) {
436
- // WE GOT THE IMAGE
437
- if (result) {
438
- UIImage *image = result;
439
- NSString *imageName = [assetID stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
440
- NSString *imagePath = [self saveImageIntoCache:image withName:imageName];
441
- completionHandler(imagePath);
442
- } else {
443
- @throw([NSException exceptionWithName:@"image not found" reason:@"image not found" userInfo:nil]);
444
- }
445
- }];
446
- }
447
-
448
- +(NSString*) saveImageIntoCache:(UIImage *)image withName:(NSString *)name {
449
- NSData *imageData = UIImageJPEGRepresentation(image, 1);
450
- NSString *path =[self generateCacheFilePath:@"jpg"];
451
- [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:NULL];
452
- return path;
453
- }
454
-
455
- /// for video
456
-
457
- +(void)getAbsoluteVideoPath:(NSString *)videoPath uuid:(NSString *)uuid completionHandler:(void (^)(NSString *absoluteImagePath))completionHandler
458
- {
459
- if([videoPath hasPrefix:@"http://"]||[videoPath hasPrefix:@"https://"])
460
- {
461
- [ImageCompressor downloadFileAndSaveToCache:videoPath uuid:uuid type:@"video" completion:^(NSString *downloadedPath) {
462
- completionHandler(downloadedPath); // Pass the downloaded path to the completionHandler
463
- }];
464
- return;
465
-
466
- }
467
- else if (![videoPath containsString:@"ph://"]) {
468
- completionHandler(videoPath);
469
- return;
470
- }
471
- NSString *assetId =[videoPath stringByReplacingOccurrencesOfString:@"ph://"
472
- withString:@""];
473
- AVFileType outputFileType = AVFileTypeMPEG4;
474
- NSString *pressetType = AVAssetExportPresetPassthrough;
475
-
476
- // Throwing some errors to the user if he is not careful enough
477
- if ([assetId isEqualToString:@""]) {
478
- NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
479
- @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
480
- return;
481
- }
482
-
483
- // Getting Video Asset
484
- NSArray* localIds = [NSArray arrayWithObjects: assetId, nil];
485
- PHAsset * _Nullable videoAsset = [PHAsset fetchAssetsWithLocalIdentifiers:localIds options:nil].firstObject;
486
-
487
- // Getting information from the asset
488
- NSString *mimeType = (NSString *)CFBridgingRelease(UTTypeCopyPreferredTagWithClass((__bridge CFStringRef _Nonnull)(outputFileType), kUTTagClassMIMEType));
489
- CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef _Nonnull)(mimeType), NULL);
490
- NSString *extension = (NSString *)CFBridgingRelease(UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension));
491
-
492
- // Creating output url and temp file name
493
- NSString *path =[self generateCacheFilePath:extension];
494
- NSURL *outputUrl = [NSURL URLWithString:[@"file://" stringByAppendingString:path]];
495
-
496
- // Setting video export session options
497
- PHVideoRequestOptions *videoRequestOptions = [[PHVideoRequestOptions alloc] init];
498
- videoRequestOptions.networkAccessAllowed = YES;
499
- videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
500
-
501
- // Creating new export session
502
- [[PHImageManager defaultManager] requestExportSessionForVideo:videoAsset options:videoRequestOptions exportPreset:pressetType resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
503
-
504
- exportSession.shouldOptimizeForNetworkUse = YES;
505
- exportSession.outputFileType = outputFileType;
506
- exportSession.outputURL = outputUrl;
507
- // Converting the video and waiting to see whats going to happen
508
- [exportSession exportAsynchronouslyWithCompletionHandler:^{
509
- switch ([exportSession status])
510
- {
511
- case AVAssetExportSessionStatusFailed:
512
- {
513
- NSError* error = exportSession.error;
514
- NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%zd", error.domain.uppercaseString, error.code];
515
- @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
516
- break;
517
- }
518
- case AVAssetExportSessionStatusCancelled:
519
- {
520
- NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
521
- @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
522
- break;
523
- }
524
- case AVAssetExportSessionStatusCompleted:
525
- {
526
- completionHandler(outputUrl.absoluteString);
527
- break;
528
- }
529
- default:
530
- {
531
- NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
532
- @throw([NSException exceptionWithName:@"Unknown status" reason:@"Unknown status" userInfo:nil]);
533
- break;
534
- }
535
- }
536
- }];
537
- }];
538
- }
539
-
540
- @end
@@ -1,28 +0,0 @@
1
- #import <UIKit/UIKit.h>
2
-
3
- typedef NS_ENUM(long, OutputType) { jpg,
4
- png
5
- };
6
-
7
- typedef NS_ENUM(long, InputType) { base64,
8
- uri
9
- };
10
-
11
- typedef NS_ENUM(long, ReturnableOutputType) { rbase64,
12
- ruri
13
- };
14
-
15
- @interface ImageCompressorOptions : NSObject
16
- + (ImageCompressorOptions *)fromDictionary:(NSDictionary *)dictionary;
17
- + (NSString *) getOutputInString:(enum OutputType*)output;
18
-
19
- @property(nonatomic, assign) Boolean autoCompress;
20
- @property(nonatomic, assign) int maxWidth;
21
- @property(nonatomic, assign) int maxHeight;
22
- @property(nonatomic, assign) float quality;
23
- @property(nonatomic, assign) enum OutputType output;
24
- @property(nonatomic, assign) enum InputType input;
25
- @property(nonatomic, assign) enum ReturnableOutputType returnableOutputType;
26
- @property(nonatomic, assign) NSString* uuid;
27
-
28
- @end
@@ -1,97 +0,0 @@
1
- #import <Foundation/Foundation.h>
2
- #import <UIKit/UIKit.h>
3
-
4
- #import "ImageCompressorOptions.h"
5
-
6
- @implementation ImageCompressorOptions
7
- + (ImageCompressorOptions*) fromDictionary:(NSDictionary *)dictionary {
8
- ImageCompressorOptions *options = [[ImageCompressorOptions alloc] init];
9
-
10
- if (dictionary == nil) {
11
- return options;
12
- }
13
-
14
- for (id key in dictionary) {
15
- id value = [dictionary objectForKey:key];
16
-
17
- if ([key isEqual:@"autoCompress"]) {
18
- options.autoCompress = [value boolValue];
19
- }else if ([key isEqual:@"maxWidth"]) {
20
- options.maxWidth = [value intValue];
21
- }else if ([key isEqual:@"maxHeight"]) {
22
- options.maxHeight = [value intValue];
23
- } else if ([key isEqual:@"quality"]) {
24
- options.quality = [value floatValue];
25
- } else if ([key isEqual:@"input"]) {
26
- [options parseInput: value];
27
- } else if ([key isEqual:@"output"]) {
28
- [options parseOutput: value];
29
- } else if ([key isEqual:@"returnableOutputType"]) {
30
- [options parseReturnableOutput: value];
31
- }else if ([key isEqual:@"uuid"]) {
32
- options.uuid=value;
33
- }
34
- }
35
-
36
- return options;
37
- }
38
-
39
- + (NSString *) getOutputInString:(enum OutputType*)output{
40
- if(output==jpg)
41
- {
42
- return @"jpg";
43
- }
44
- else
45
- {
46
- return @"png";
47
- }
48
- }
49
-
50
- - (instancetype) init {
51
- self = [super init];
52
-
53
- if (self) {
54
- self.autoCompress = false;
55
- self.maxWidth = 1280;
56
- self.maxHeight = 1280;
57
- self.quality = 0.8f;
58
- self.input = uri;
59
- self.output = jpg;
60
- self.returnableOutputType = uri;
61
- self.uuid = uuid;
62
- }
63
-
64
- return self;
65
- }
66
-
67
- @synthesize autoCompress;
68
- @synthesize maxWidth;
69
- @synthesize maxHeight;
70
- @synthesize quality;
71
- @synthesize input;
72
- @synthesize output;
73
- @synthesize returnableOutputType;
74
- @synthesize uuid;
75
-
76
- - (void) parseInput:(NSString*)input {
77
- NSDictionary *inputTranslations = @{ @"base64": @(base64), @"uri": @(uri) };
78
- NSNumber *enumValue = [inputTranslations objectForKey: input];
79
-
80
- self.input = [enumValue longValue];
81
- }
82
-
83
- - (void) parseReturnableOutput:(NSString*)input {
84
- NSDictionary *inputTranslations = @{ @"base64": @(rbase64), @"uri": @(ruri) };
85
- NSNumber *enumValue = [inputTranslations objectForKey: input];
86
-
87
- self.returnableOutputType = [enumValue longValue];
88
- }
89
-
90
- - (void) parseOutput:(NSString*)output {
91
- NSDictionary *outputTranslations = @{ @"jpg": @(jpg), @"png": @(png) };
92
- NSNumber *enumValue = [outputTranslations objectForKey: output];
93
-
94
- self.output = [enumValue longValue];
95
- }
96
-
97
- @end
@@ -1,16 +0,0 @@
1
- #import <Foundation/Foundation.h>
2
-
3
- typedef void (^DownloadCompleteCallback)(NSString *filePath);
4
- typedef void (^ErrorCallback)(NSError*);
5
- typedef void (^ProgressCallback)(NSNumber*);
6
-
7
- @interface Downloader : NSObject <NSURLSessionDelegate, NSURLSessionDownloadDelegate>
8
-
9
- @property (nonatomic, copy) ProgressCallback globalProgressCallback;
10
- @property (nonatomic, copy) DownloadCompleteCallback globalDownloadCompleteCallback;
11
- @property (nonatomic, copy) ErrorCallback globalErrorCallback;
12
-
13
- - (NSString *)downloadFile:(NSString *)fromUrl downloadCompleteCallback:(DownloadCompleteCallback)downloadCompleteCallback progressCallback:(ProgressCallback)progressCallback errorCallback:(ErrorCallback)errorCallback;
14
- - (NSString *)generateCacheFilePath:(NSString *)extension;
15
-
16
- @end