我从网址获取图片并保存到文件。 我保存和加载的代码:
-(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 {
NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
}
}
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
return result;
}
下载图像,保存到文件并从文件加载 成功地工作。但我希望得到我保存的所有图像 文件。所以我不想指定图像名称。我怎么能这样做?
答案 0 :(得分:1)
你必须知道你想要读什么。可能有很多方法 - 这里有两个:
存储每个文件的文件名并迭代这些文件名。
将图像存储在某个目录中并循环遍历目录内容。
答案 1 :(得分:1)
当您保存图像时,请制定一些命名约定,即image01.png,image02.png,image03.png,这样当您加载它们时,您可以简单地遍历For循环并调用函数已写道:
for (int i = 1; i <= imagesCount; i++) {
NSString* twoDigitNumber;
if (i < 10) {
twoDigitNumber = [NSString stringWithFormat:@"0%d", i];
}
else {
twoDigitNumber = [NSString stringWithFormat:@"%d", i];
}
NSString* imageName = [NSString stringWithFormat:@"image%@", twoDigitNumber];
UIImage* image = [self loadImage:imageName inDirectory:......]; // Complete your code here
}