问题
Possible Duplicate:
display image from URL retrieved from ALAsset in iPhone
In my Application I need to get specific image from Photo Library,
with use of didFinishPickingMediaWithInfo i am able to get the Imagename and ImagePath.
I am storing Imagename, ImagePath in Database.
But, how to show that specific image with use of the Imagename or ImagePath in Imageview from Photo Library?
回答1:
Please make use of ALAssetLibrary
. To do this, add the AssetsLibrary.framework
to your project and write the below code.
Your file name should look like assets-library://asset/asset.JPG?id=1000000194&ext=JPG
NSString *fileName = @"assets-library://asset/asset.JPG?id=1000000194&ext=JPG";
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
UIImage *images = nil;
if (iref)
{
images = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
//doing UI operation on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
yourImageView.image = images;
});
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(@"can't get image");
};
NSURL *asseturl = [NSURL URLWithString:fileName];
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];
Note:
After the upgrade to iOS 5 and a code refactoring to make use of ARC, you will get an error as
invalid attempt to access ALAssetPrivate past the lifetime of its owning ALAssetsLibraryrefactoring to make use of ARC
To resolve this, add a static method to retrieve a shared instance of ALAssetLibrary
class.
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred, ^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
Then, access it using [MyClass defaultAssetsLibrary];
[[MyClass defaultAssetsLibrary] assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];
回答2:
If you have image path with you than you can use the following code. Lets take imagePath as NSString Variable that contains image path including image name.
NSData *thedata=[[NSData alloc]initWithContentsOfFile:imagePath];
UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageWithData:thedata]];
Hope it helps.
来源:https://stackoverflow.com/questions/11322289/how-to-show-the-specific-image-from-photolibrary