我正在尝试保存图像 from here到设备的文档目录,但我的方法不起作用。 我不得不提到这种方法适用于图片 like this :
我已经使用 iExplorer 检查了文档的目录,并且图像以正确的名称保存到正确的路径,我也尝试手动下载图像并将其放入文档目录并且成功了。我下载的图像大小为 900kbyte,但代码下载的图像为 3.1mbyte。
我的代码是:
UIImage *staticResortMap = [self downloadImageWithStringURL:resort.staticPhotoPath];
staticPhotoPath = [_fileManager saveImage:staticResortMap usingName:kImageBaseNameResortStaticMap];
- (UIImage *)downloadImageWithStringURL:(NSString *)stringURL {
NSURL *photoURL = [NSURL URLWithString:stringURL];
NSData *data = [[NSData alloc] initWithContentsOfURL:photoURL];
return [[UIImage alloc] initWithData:data];
}
- (NSString *)saveImage:(UIImage *)image usingName:(NSString *)name {
NSString *directory = [_documentsDirectory stringByAppendingPathComponent:kDirectoryNameResortResources];
NSError * error = nil;
[_fileManager createDirectoryAtPath:directory
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (error != nil) {
NSLog(@"error creating directory: %@", error);
}
NSString *path = [directory stringByAppendingPathComponent:name];
[UIImageJPEGRepresentation(image, .9f) writeToFile:path atomically:YES];
return path;
}
我试过像这样使用保存的图像:
UIImage *image = [UIImage imageNamed:@"/var/mobile/Applications/0C62F621-C823-4DE2-B1CD-796EBAA459FB/Documents/resort_resources/static_map_image.jpg"];
UIImage *image1 = [UIImage imageNamed:@"/var/mobile/Applications/0C62F621-C823-4DE2-B1CD-796EBAA459FB/Documents/resort_resources/static_map_image.png"];
UIImage *image2 = [UIImage imageNamed:@"static_map_image.jpg"];
UIImage *image3 = [UIImage imageNamed:@"static_map_image.png"];
我的问题是,当我将图像保存到文档目录并尝试使用函数 [UIImage imagenamed:""]
进行分配时,该函数返回 nil。但是当我从互联网上的其他 URL 保存图像时,它就可以工作了。我知道这听起来很傻。
我做错了什么?
最佳答案
像这样检索图像文档子目录:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocumentsDir = [paths objectAtIndex:0];
NSString *filePath = [pathToDocumentsDir stringByAppendingPathComponent:@"resort_resources"]; // Get path of your subdirectory
filePath = [filePath stringByAppendingPathComponent:@"static_map_image.jpg"];// Full path of your image
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
关于ios - 使用 UIImageJPEGRepresentation 保存图像并用作 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20300642/