我使用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