从iOS照片库uri获取base64照片

时间:2017-05-14 19:38:01

标签: ios objective-c react-native

我在React Native中构建应用程序,我需要使用照片uri(例如photos://A2B9B28B-9A3E-4190-BCA0-B11F1E587085/L0/002)将照片库中的图像作为base64。我最初使用资产库,但我已经更新了我的应用程序以使用新的照片库,我正在努力让它发挥作用。

我的旧资产库方法是:

{
  NSURL *url = [[NSURL alloc] initWithString:input];
  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
  [library assetForURL:url resultBlock:^(ALAsset *asset) {
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    CGImageRef imageRef = [rep fullScreenImage];
    NSData *imageData = UIImagePNGRepresentation([UIImage imageWithCGImage:imageRef]);
    NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
    callback(@[[NSNull null], base64Encoded]);
  } failureBlock:^(NSError *error) {
    NSLog(@"that didn't work %@", error);
    callback(@[error]);
  }];
}

2 个答案:

答案 0 :(得分:2)

它与您已有的代码基本相同,它刚刚分为两部分。首先使用ID获取HttpPost request = new HttpPost(url); //request.addHeader("Authorization", "Basic"); // if we need authorization String fileName="C:\\Desert.jpg"; File file = new File(fileName); FileBody fileBody = new FileBody(new File(fileName), ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("X-FPA-Meta-File-Name", "test.jpg"); builder.addTextBody("Username","a"); builder.addTextBody("Password","a"); builder.addBinaryBody("part1", file, ContentType.DEFAULT_BINARY, "java.jpg"); final HttpEntity entity = builder.build(); request.setEntity(entity); HttpResponse response = null; HttpClient httpclient = HttpClientBuilder.create().build(); try { response = httpclient.execute(request); } catch (SocketException se) { System.out.println(se); throw se; } ,然后使用PHAsset从该资产中获取图片。

  • 要从库中获取PHImageManager

PHAsset

此方法是同步的,会立即返回[+ (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options;的数组,但这些资源不包含任何图像数据。

  • 下次使用

PHAsset获取图片。这与ALAssetsLibrary方法类似,是异步的。使用[PHImageManager defaultManager]

代码应该是这样的(显然你必须填写你的应用程序的错误代码和错误域)):

- (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset  options:(PHImageRequestOptions *)options  resultHandler:(void (^)(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info))resultHandler;

答案 1 :(得分:1)

您可以在PHAsset + (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options;

中看到api