您的位置:首页 > 理论基础 > 计算机网络

iOS-从网络下载图片,保存,并用imageview从保存中显示

2014-11-15 13:59 549 查看
-(UIImage *) getImageFromURL:(NSString *)fileURL {
     NSLog(@"执行图片下载函数");
     UIImage * result; NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]]; 
     result = [UIImage imageWithData:data];
       return result;
}

-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
       if ([[extension lowercaseString] isEqualToString:@"png"])

             [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString      
                stringWithFormat:@"%@.%@",
imageName, @"png"]] options:NSAtomicWrite error:nil]; 
     } else if ([[extension lowercaseString] isEqualToString:@"jpg"]
|| [[extension lowercaseString] isEqualToString:@"jpeg"]) {   
              [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString     
                stringWithFormat:@"%@.%@",
imageName, @"jpg"]] options:NSAtomicWrite error:nil]; 
     } else {  //ALog(@"Image Save
Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
            NSLog(@"文件后缀不认识");
     }
}

-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath { 
     UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@",
directoryPath, fileName,             
            extension]];
       return result;
}

NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
 NSLog(@"保存路径:%@",documentsDirectoryPath);
   //Get Image From URL
UIImage * imageFromURL = [self getImageFromURL:@"http://file.duteba.com/phone/2009/04/5/ftGxL8kcUL.jpg"];
   //Save Image to Directory
[self saveImage:imageFromURL withFileName:@"MyImage" ofType:@"jpg" inDirectory:documentsDirectoryPath];
   //Load Image From Directory
UIImage * imageFromWeb = [self loadImage:@"MyImage" ofType:@"jpg" inDirectory:documentsDirectoryPath];
 [img setImage:imageFromWeb];
   //取得目录下所有文件名 
 NSArray *file = [[[NSFileManager alloc] init] subpathsAtPath:documentsDirectoryPath];
   //NSLog(@"%d",[file count]);
NSLog(@"%@",file); 
   //如何获取下载的文件的完整路径?
NSString *documentsDirectory2 = [path2 objectAtIndex:0];
  //path数组里貌似只有一个元素  //字符串拼接得到文件完整路径
NSString *filestr = @"/MyImage.jpg";
NSString *newstr = [documentsDirectory2 stringByAppendingString:filestr]; 
 NSLog(@"完整路径是:%@",newstr); 
 NSData *dd = [NSData dataWithContentsOfFile:newstr]; 
 [img222 setImage:[UIImage imageWithData:dd]];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: