objective-c - 从 PHAsset(或 assets-library://)获取 UIImage
问题描述
我正在尝试从 PHAsset 或资产库生成 UIImage。我的代码是这样的:
NSString *path = [self.options valueForKey:@"path"];
NSURL *localurl = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:localurl];
UIImage *image = [[UIImage alloc] initWithData:data];
但是 UIImage 是零。我可以将路径设置为ph://
或assets-library://
。
谢谢!
解决方案
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
NSMutableArray *arrPhassets=[[NSMutableArray alloc]init];
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//here you will get phassets of images from the device photo library.you have to store it in the mutable array like this.
[arrPhassets addObject:asset];
}];
//here you will have array of phassets for images.
//now we will extract image from the phasset for one phasset.
PHAsset *as1=arrPhassets[0];
PHCachingImageManager *imagemanager=[[PHCachingImageManager alloc]init];
[imagemanager requestImageForAsset:as1 targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//here "result" is the image for asset as1.
UIImage *image=result;
}];
推荐阅读
- android - 会话“应用程序”:安装未成功。无法安装应用程序:SHELL_UNRESPONSIVE
- java - 显示具有多个航点的两点之间的路线 Android Here Map Lite Edition
- c++ - 如何使用 VBO 数据作为顶点着色器中的位置数据和统一数据作为片段着色器中的颜色数据
- javascript - JS For循环计数器在嵌套循环中不起作用
- android - 获取 4 个按钮以具有相同的 autoSize Android (Kotlin)
- c - 在 C 程序中使用带有指针数组的 strcmp() 函数
- github - 如何使 GitHub Actions 相互通信
- javascript - Gulp 4 watch() TypeError:期望一个字符串
- php - 使用PHP在html表中打印多维数组数据
- oracle - IO 错误:网络适配器无法从 linux 中的 jsp tomcat 建立连接