可能重复: display image from URL retrieved from ALAsset in iPhone
在我的应用程序中,我需要从照片库获取特定的图像,
通过使用didFinishPickingMediaWithInfo,我能够获得Imagename和ImagePath。
我正在数据库中存储Imagename,ImagePath。
但是,如何使用图片库中的Imageview中的Imagename或ImagePath来显示特定的图像呢?
发布于 2012-07-04 05:13:18
请使用ALAssetLibrary。为此,请将AssetsLibrary.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之后,您将得到一个错误,如
使用ARC访问ALAssetPrivate超过其拥有的ALAssetsLibraryrefactoring的生存期的无效尝试
若要解决此问题,请添加一个静态方法来检索ALAssetLibrary类的共享实例。
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred, ^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}然后,使用[MyClass defaultAssetsLibrary];访问它
[[MyClass defaultAssetsLibrary] assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];发布于 2012-07-04 04:30:33
如果您有图像路径,则可以使用以下代码。让我们将imagePath作为包含图像路径(包括图像名称)的NSString变量。
NSData *thedata=[[NSData alloc]initWithContentsOfFile:imagePath];
UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageWithData:thedata]];希望能帮上忙。
https://stackoverflow.com/questions/11322289
复制相似问题