ios - 使用 UIImageJPEGRepresentation 保存图像并用作 UIImage

标签 ios objective-c swift uiimageview uiimage

我正在尝试保存图像 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/

相关文章:

ios - Swift ios 中的自定义谷歌地图标记图标图像

ios - UISearchBar 忽略编程约束

ios - 如何创建带有列标题和行标题的 UICollectionView?

cocoa - Swift 中的数组如何知道它是否包含元素?

objective-c - SBTableAlert 崩溃

ios - Swift 3 添加新联系人电话和电子邮件信息

objective-c - 为什么在Objective-C和iOS中,[[NSMutableArray alloc] init]发出警告,但NSMutableArray.new没有给出警告?

ios - 使用 Codable 解码具有多个 key 的 JSON

swift - 以编程方式在 ScrollView 中获取 UIImageView 时遇到问题

ios - 在 Swift 中实现用于选择的 UIButton