|
// |
|
// ImageToBase64.m |
|
// |
|
// Created by Mike Fogg on 6/28/18. |
|
// |
|
|
|
#import "ImageToBase64.h" |
|
|
|
@implementation ImageToBase64 |
|
|
|
//export the name of the native module as 'ImageToBase64' since no explicit name is mentioned |
|
RCT_EXPORT_MODULE(); |
|
|
|
//exports a method convert to javascript |
|
RCT_EXPORT_METHOD(convertToBase64: (NSDictionary*) options |
|
resolve:(RCTPromiseResolveBlock) resolve |
|
reject:(RCTPromiseRejectBlock) reject) |
|
{ |
|
NSString *uri = options[@"assetPath"]; |
|
|
|
// Take the asset path we get, and get the local identifier of the image |
|
NSURLComponents *components = [NSURLComponents componentsWithString:uri]; |
|
NSArray *queryItems = components.queryItems; |
|
NSString *assetId = [self valueForKey:@"id" fromQueryItems:queryItems]; |
|
|
|
// Go get a list of assets with this identifier (should be one?) |
|
PHFetchResult* assetList = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:NULL]; |
|
PHAsset *imageAsset = [assetList firstObject]; |
|
|
|
// Go get the actual image data |
|
PHImageManager *imageManager = [PHImageManager defaultManager]; |
|
[imageManager requestImageDataForAsset:imageAsset options:NULL resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { |
|
UIImage *image = [UIImage imageWithData:imageData]; |
|
resolve(@{ @"base64": [self encodeToBase64String: image] }); |
|
}]; |
|
} |
|
|
|
- (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems |
|
{ |
|
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key]; |
|
NSURLQueryItem *queryItem = [[queryItems |
|
filteredArrayUsingPredicate:predicate] |
|
firstObject]; |
|
return queryItem.value; |
|
} |
|
|
|
-(NSString *) encodeToBase64String:(UIImage *)image { |
|
return [UIImageJPEGRepresentation(image, 1.0f) base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength]; |
|
} |
|
|
|
@end |