我有一个来自 Json 的数组 url 图像。
我想在应用程序中下载、保存和显示图像。检查应用程序中是否存在图像。
你能帮助我吗!
预先感谢
代码下载,保存并显示:->我不知道检查图像是否存在使用它:
for (int i=0; i<[self.imageURLs count]; i++) {
if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"img%d.jpg",i]]) {
NSLog(@"file exists at the path");
}
else
NSLog(@"file doesnt exist");
int y_lblLogo = i==0 ? 45 : (20 * (i+1)) - 15 ;
UIImage * imageFromURL = [self getImageFromURL:[self.imageURLs objectAtIndex:i]];
[self saveImage:imageFromURL withFileName:[NSString stringWithFormat:@"img%d",i] ofType:@"png" inDirectory:documentsDirectoryPath];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(200 * i, 0, 100, 100)];
UIImage * imageFromWeb = [self loadImage:[NSString stringWithFormat:@"img%d",i] ofType:@"png" inDirectory:documentsDirectoryPath];
imgView.image = imageFromWeb;
[imgView drawRect:CGRectMake(0,y_lblLogo,70.f,30.f)];
//[self.view addSubview:imgView];
}
-(UIImage *) getImageFromURL:(NSString *)fileURL {
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 {
}
}
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
return result;
}