iOS 根據圖片URL從本地相冊獲取圖片


最近做一個聊天的項目,需要發送圖片后讀取本地圖片顯示到列表里。剛開始的時候,天真的認為可以用SDWebImage直接加載,然后並不能行。

於是在網上搜了搜,如何根據從相冊獲取的UIImagePickerControllerReferenceURL讀取圖片, 代碼如下:

#import "ViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
- (IBAction)showImagePickerVC:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];   
}

 彈出圖片選擇器

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

 回調

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%@", info);
    NSURL *imagePath = info[@"UIImagePickerControllerReferenceURL"];

    if ([[[imagePath scheme] lowercaseString] isEqualToString:@"assets-library"]) {
        
        // Load from asset library async
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            @autoreleasepool {
                @try {
                    ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
                    [assetslibrary assetForURL:imagePath
                                   resultBlock:^(ALAsset *asset){
                                       ALAssetRepresentation *rep = [asset defaultRepresentation];
                                       CGImageRef iref = [rep fullScreenImage];
                                       if (iref) {
                                           //進行UI修改
                                           dispatch_sync(dispatch_get_main_queue(), ^{
                                               _imageView.image = [[UIImage alloc] initWithCGImage:iref];
                                           });
                                           
                                        }
                
                                   }
                                  failureBlock:^(NSError *error) {
                                      
                                      NSLog(@"從圖庫獲取圖片失敗: %@",error);
                                      
                                  }];
                } @catch (NSException *e) {
                    NSLog(@"從圖庫獲取圖片異常: %@", e);
                }
            }
        });
        
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM