【发布时间】: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