Iphone 如何显示PhotoLibrary中的特定图像?

Iphone 如何显示PhotoLibrary中的特定图像?,iphone,objective-c,cocoa-touch,ios4,Iphone,Objective C,Cocoa Touch,Ios4,可能重复: 在我的应用程序中,我需要从照片库中获取特定图像 使用didfishpickingMediaWithInfo我可以获得图像名称和图像路径 我正在数据库中存储Imagename、ImagePath 但是,如何在照片库的Imageview中使用Imagename或ImagePath显示特定图像?如果您随身携带图像路径,则可以使用以下代码。让我们将imagePath作为NSString变量,该变量包含包含图像名称的图像路径 NSData *thedata=[[NSData alloc

可能重复:

在我的应用程序中,我需要从照片库中获取特定图像

使用didfishpickingMediaWithInfo我可以获得图像名称和图像路径

我正在数据库中存储Imagename、ImagePath


但是,如何在照片库的Imageview中使用Imagename或ImagePath显示特定图像?

如果您随身携带图像路径,则可以使用以下代码。让我们将imagePath作为NSString变量,该变量包含包含图像名称的图像路径

   NSData *thedata=[[NSData alloc]initWithContentsOfFile:imagePath];
     UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageWithData:thedata]];

希望能有所帮助。

请使用
ALAssetLibrary
。为此,请将
assetsbrary.framework
添加到项目中,并编写以下代码

您的文件名应该类似于
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];
注意:

升级到iOS 5并使用ARC进行代码重构后,您将得到一个错误,如下所示:

在ALAssetPrivate的生存期内访问ALAssetPrivate的尝试无效 利用ARC进行图书馆重构

要解决此问题,请添加一个静态方法来检索
ALAssetLibrary
类的共享实例

+ (ALAssetsLibrary *)defaultAssetsLibrary {
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library; 
}
然后,使用
[MyClass DefaultAssetLibrary]访问它

[[MyClass defaultAssetsLibrary] assetForURL:asseturl 
                   resultBlock:resultblock   
                  failureBlock:failureblock];

这是在图像选择之后吗?是否在UIImageView中显示所选图像?您可以像这样将图像传递给UIImage。UIImage*image=[info objectForKey:UIImagePickerControllerOriginalImage];//对于原始图像