How to save path of image picked from UIImagePicke

2019-04-16 01:40发布

I need to save path of the image picked from server and later access the path to show that image on user click by database retrival.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
      NSString *urlPath =  [info objectForKey:@"UIImagePickerControllerReferenceURL"]absoluteString];
}

and saving it to database.

It saved as assets-library://asset/asset.JPG?id=E1136225-97DE-4BF4-A864-67E33D60737A&ext=JPG

then I want to import to Imageview

 UIImageView *iv = [[UIImageView alloc]init];
 iv.image = [UIimage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagepath]]];

But it is not working

2条回答
乱世女痞
2楼-- · 2019-04-16 01:53

Try this:

  typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
    typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);    

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){

     ALAssetRepresentation *rep = [myasset defaultRepresentation];
     CGImageRef iref = [rep fullResolutionImage];

     if (iref){

            UIImage *myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
            [fileImage addObject:myImage];

             }      
    };      

    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror){

         //failed to get image.
    };                          

    ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
    [assetslibrary assetForURL:[filePath objectAtIndex:0] resultBlock:resultblock failureBlock:failureblock];

Note: Make sure your [filePath objectAtIndex:0] will be a NSUrl object. Else convert it to NSUrl

Example:

ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];

NSURL myAssetUrl = [NSURL URLWithString:[filePath objectAtIndex:0]];

assetslibrary assetForURL:myAssetUrl resultBlock:resultblock failureBlock:failureblock];
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-16 02:12

Use assetForURL:resultBlock:failureBlock: method of ALAssetsLibrary class to retrieve image by URL. There is more info: http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAssetsLibrary_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40009722

UPD:

ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib assetForURL: url resultBlock: ^(ALAsset *asset) {
    ALAssetRepresentation *r = [asset defaultRepresentation];
    self.imgView.image = [UIImage imageWithCGImage: r.fullResolutionImage];
}
    failureBlock: nil];

Where is url is your cached URL

查看更多
登录 后发表回答