使用UIImageJPEGRepresentation保存图像并使用UIImage

时间:2013-11-30 13:10:14

标签: ios objective-c swift uiimageview uiimage

我正在尝试将图片from here保存到设备的Documents目录中,但我的方法无效。 我必须提到这种方法适用于图片like this

我使用iExplorer检查了文档的目录,图像以正确的名称保存到正确的路径中我也试图手动下载图像并将其放到Documents目录中并且工作正常。我下载的图片大小为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"];

我的问题是,当我将图像保存到Document目录并且我尝试使用函数[UIImage imagenamed:""]进行分配时,函数返回nil。但是,当我从互联网上保存其他网址的图像时正在运行。我知道这听起来很傻。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

像这样检索图像文档子目录:

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];

答案 1 :(得分:0)

使用 Swift

尝试此操作
// Get a document url (path)
func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

if let image = UIImage(named: "example.png") {
    if let data = UIImageJPEGRepresentation(image, 0.8) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}