从PHAsset(或Assets-library://)获取UIImage

问题描述 投票:-1回答:1

我正在尝试从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为nil。我可以将路径设置为ph://assets-library://

谢谢!

objective-c uiimage
1个回答
0
投票
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;

}];
© www.soinside.com 2019 - 2024. All rights reserved.