[英]Get base64 photo from iOS photo library uri
我正在使用React Native构建应用程序,我需要使用照片uri
从照片库中获取图像作为base64(例如photos://A2B9B28B-9A3E-4190-BCA0-B11F1E587085/L0/002
)。 我最初使用资产库,但我已经更新了我的应用程序以使用新的照片库,我正在努力让它工作。
我的旧资产库方法是:
{
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]);
}];
}
它与您已有的代码基本相同,它刚刚分为两部分。 首先使用id获取PHAsset
,然后使用PHImageManager
从该资产获取图像。
PHAsset
[+ (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options;
此方法是同步的,并立即返回PHAsset
数组,但这些资产不包含任何图像数据。
[PHImageManager defaultManager]
获取图像。 这与ALAssetsLibrary方法类似,是异步的。 use - (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset options:(PHImageRequestOptions *)options resultHandler:(void (^)(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info))resultHandler;
代码应该是这样的(显然你必须为你的应用程序填写你的错误代码和错误域)):
PHFetchResult* results = [PHAsset fetchAssetsWithLocalIdentifiers:@[input] options:nil];
PHAsset *asset = [results firstObject];
if (asset) {
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
if (imageData){
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
callback(@[[NSNull null], base64Encoded]);
}else{
NSError* error = info[PHImageErrorKey];
if (!error) {
error = [NSError errorWithDomain:@"" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"image not found"}];
}
callback(nil, error);
}
}];
}else{
NSError* error = [NSError errorWithDomain:@"" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"asset not found"}];
callback(nil, error);
}
您可以在PHAsset + (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options;
看到api :( + (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.