【问题标题】:full image asset not converting to base64 string完整图像资产未转换为 base64 字符串
【发布时间】:2015-11-05 18:19:05
【问题描述】:

我正在使用 react-native 将图像上传到服务器。为此,我需要从 CameraRoll 中获取图像 uri 并将其转换为 base64 字符串,然后将其上传。由于它的反应是原生的,因此我理解其中有相当一部分是在 javascript 中完成的。但是,从asset到base64字符串的转换发生在objective-c中,我不是很流利,所以我依赖于来自不同开发人员的一些代码。一切正常,除了图像的转换是针对原始缩略图而不是原始缩略图进行的。我想转换实际的完整图像。

@interface ReadImageData : NSObject <RCTBridgeModule>
@end

@implementation ReadImageData

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(readImage:(NSString *)input callback:(RCTResponseSenderBlock)callback)
{

  // Create NSURL from uri
  NSURL *url = [[NSURL alloc] initWithString:input];

  // Create an ALAssetsLibrary instance. This provides access to the
  // videos and photos that are under the control of the Photos application.
  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

  // Using the ALAssetsLibrary instance and our NSURL object open the image.
  [library assetForURL:url resultBlock:^(ALAsset *asset) {

    // Create an ALAssetRepresentation object using our asset
    // and turn it into a bitmap using the CGImageRef opaque type.
    CGImageRef imageRef = [asset thumbnail];
    // Create UIImageJPEGRepresentation from CGImageRef
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.5);

    // Convert to base64 encoded string
    NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];

    callback(@[base64Encoded]);

  } failureBlock:^(NSError *error) {
    NSLog(@"that didn't work %@", error);
  }];



}
@end

显然,资产转换发生在[asset thumbnail]。我查阅了文档并尝试将其更改为[asset originalAsset],它应该返回完整的图像,但我得到了一个隐式转换错误。即:

将目标 C 指针类型“ALAsset”隐式转换为 C 指针类型“CGImageRef”需要桥接转换

我尝试使用建议的解决方案,即:

(__bridge CGImageRef)([asset originalAsset])

但是,这会导致我的应用程序因以下错误而崩溃:

NSInvalidArgumentException,原因:-[__NSPlaceholderArray initWithObjects:count:]: 尝试从 objects[0] 插入 nil 对象

所以我不确定如何进行。有参考代码的完整文章是here

【问题讨论】:

    标签: ios objective-c reactjs base64 react-native


    【解决方案1】:

    代替:

    CGImageRef imageRef = [asset thumbnail];
    

    添加这两行:

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    CGImageRef imageRef = [rep fullScreenImage];
    

    【讨论】:

      【解决方案2】:

      我查阅了文档并尝试将其更改为 [asset originalAsset],它应该会返回完整图像

      不,不应该。您需要更仔细地查看文档。 originalAsset 只是指向另一个 ALAsset 的指针,以防此资产已被编辑。 不是图片。 ALAsset 不是图像。

      要访问图像,请通过资产的defaultRepresentation。这是一个 ALAssetRepresentation。现在你可以得到全分辨率的CGImage了。

      【讨论】:

      • 另外,不推荐使用 ALAsset;此时您应该使用 Photo Kit 库。
      • 这不是答案,是评论。
      • 那里!现在我完成了。当然,我所做的只是你应该做的——我阅读了文档。 :)
      • 这个答案会导致构建失败。当我尝试将它与 CGImage 桥耦合时,它给了我在问题中提到的相同错误。
      • 答案不会“导致”任何事情。它不会为您编写代码。我只是回答您提出的问题 - 即,当您尝试将 ALAsset 的 originalAsset 视为图像时,为什么要尝试将其视为崩溃。这是因为它不是图像。我向你展示了图像所在的位置。想法取决于你。 (当然,阅读文档也取决于您,您也没有这样做。)
      猜你喜欢
      • 2018-09-07
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2020-10-03
      • 2011-06-17
      相关资源
      最近更新 更多