iOS 根据图片URL从本地相册获取图片

电玩女神 2022-01-05 16:19 520阅读 0赞

最近做一个聊天的项目,需要发送图片后读取本地图片显示到列表里。刚开始的时候,天真的认为可以用SDWebImage直接加载,然后并不能行。

于是在网上搜了搜,如何根据从相册获取的UIImagePickerControllerReferenceURL读取图片, 代码如下:

  1. #import "ViewController.h"
  2. #import <AssetsLibrary/AssetsLibrary.h>
  3. @interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
  4. - (IBAction)showImagePickerVC:(id)sender;
  5. @property (weak, nonatomic) IBOutlet UIImageView *imageView;
  6. @end
  7. @implementation ViewController
  8. - (void)viewDidLoad {
  9. [super viewDidLoad];
  10. }

弹出图片选择器

  1. - (IBAction)showImagePickerVC:(id)sender {
  2. UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
  3. imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  4. imagePickerVC.allowsEditing = YES;
  5. imagePickerVC.delegate = self;
  6. [self presentViewController:imagePickerVC animated:YES completion:nil];
  7. }

回调

  1. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  2. {
  3. NSLog(@"%@", info);
  4. NSURL *imagePath = info[@"UIImagePickerControllerReferenceURL"];
  5. if ([[[imagePath scheme] lowercaseString] isEqualToString:@"assets-library"]) {
  6. // Load from asset library async
  7. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  8. @autoreleasepool {
  9. @try {
  10. ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
  11. [assetslibrary assetForURL:imagePath
  12. resultBlock:^(ALAsset *asset){
  13. ALAssetRepresentation *rep = [asset defaultRepresentation];
  14. CGImageRef iref = [rep fullScreenImage];
  15. if (iref) {
  16. //进行UI修改
  17. dispatch_sync(dispatch_get_main_queue(), ^{
  18. _imageView.image = [[UIImage alloc] initWithCGImage:iref];
  19. });
  20. }
  21. }
  22. failureBlock:^(NSError *error) {
  23. NSLog(@"从图库获取图片失败: %@",error);
  24. }];
  25. } @catch (NSException *e) {
  26. NSLog(@"从图库获取图片异常: %@", e);
  27. }
  28. }
  29. });
  30. }
  31. [picker dismissViewControllerAnimated:YES completion:nil];
  32. }

转载于:https://www.cnblogs.com/pretty-guy/p/4548761.html

发表评论

表情:
评论列表 (有 0 条评论,520人围观)

还没有评论,来说两句吧...

相关阅读