-(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); //如何获取下载的文件的完整路径?
把已经下载的jpg用imageview显示
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]];