////////下载图片////////
//方法一(暴力而有效,必须下载完才进入页面)同步
NSURL *url = [NSURL URLWithString:@"http://cc.cocimg.com/bbs/attachment/upload/07/128707.png"];
UIImage *imga = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
img1.image=imga;
//方法二 (需要等下载完才显示,但照样可以进入页面)异步
NSString *[email protected]"http://tp1.sinaimg.cn/2122519000/50/5620445947/1";
UIImageFromURL( [NSURL URLWithString:url2], ^( UIImage * image )
{
img2.image=image;
NSLog(@"----%@",image);
}, ^(void){
NSLog(@"error!");
} );
///////下面是关于读取与写入Documents的//////////
UIImage *bear=[UIImage imageNamed:@"image.png"];
//Document创建一个列表中的目录搜索路径。获得应用程序的Documents文件夹
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
// NSString *paths = [pathArray lastObject];
NSString *uniquePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
stringByAppendingPathComponent:@"image.png"];
/*写入图片*/
//帮文件起个名
//NSString *uniquePath=[[paths stringByAppendingPathComponent:@"image" ] stringByAppendingPathComponent:@"image.png"];
//将图片写到Documents文件中
//拿到PNG格式的图像对象
[UIImagePNGRepresentation(bear) writeToFile: uniquePath atomically:YES];
/*读取入图片*/
//因为拿到的是个路径,所以把它加载成一个data对象
NSData *data=[NSData dataWithContentsOfFile:uniquePath];
//直接把该图片读出来
img3.image=[UIImage imageWithData:data];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[img1 release];
[img2 release];
[img3 release];
[super dealloc];
}
#pragma mark - 方法二
//
void UIImageFromURL( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) )
{
//提出了一个用于在调度队列异步执行块并立即返回。
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
{
NSData * data = [[[NSData alloc] initWithContentsOfURL:URL] autorelease];
UIImage * image = [[[UIImage alloc] initWithData:data] autorelease];
//返回应用程序的主线程关联的串行调度队列。
dispatch_async( dispatch_get_main_queue(), ^(void){
if( image != nil )
{
imageBlock( image );
} else {
errorBlock();
}
});
});
}
@end