我使用react-native将图像上载到服务器。为了做到这一点,我需要从CameraRoll中获取图像URI并将其转换为base64字符串,然后将其上传。由于它的反应 - 原生一小部分这是得到了JavaScript的,我明白了。但是,从资产到base64字符串的转换发生在objective-c中,我不太流利,所以我依赖来自不同开发人员的一些代码。一切正常,除了图像的转换发生在原始缩略图而不是原始本身之外。我想转换实际的完整图像。完整图像资产不转换为base64字符串
@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:]:尝试插入nil对象fr om objects [0]
所以我不知道如何继续。具有引用代码的完整文章是here。
另外,ALAsset已不再被此时您应该使用Photo Kit库。 – matt
这不是一个答案,它的评论。 – nmac
也不完成。请冷却你的飞机,请... – matt