如何从应用程序的Documents文件夹中加载.png图像

时间:2014-11-10 09:22:49

标签: ios objective-c iphone image

我的应用的Documents文件夹中有.png图像,但是当我尝试加载它们时它不起作用:/

我有这个类用于保存和加载的方法:

UIImage + loadScan.h:

#import <UIKit/UIKit.h>

@interface UIImage (loadScan)

- (void)saveScan:(NSString*)name;

- (UIImage *)loadScan:(NSString*)name;

@end

.m:

#import "UIImage+loadScan.h"

@implementation UIImage (loadScan)

#pragma SAVE AND LOAD

- (void)saveScan:(NSString*)name{
    if (self != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          [NSString stringWithString:name] ];
        NSData* data = UIImagePNGRepresentation(self);
        [data writeToFile:path atomically:YES];
    }
}

- (UIImage *)loadScan:(NSString*)name{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [NSString stringWithFormat:@"%@/%@", documentsDirectory, name];
    NSLog(@"loading %@", path);

    NSData *imgData = [NSData dataWithContentsOfFile:path];
    UIImage *image = [[UIImage alloc] initWithData:imgData];

    //UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}

@end

saveScan方法运行良好:

[image saveScan:[NSString stringWithFormat:@"%@.png", imgName]];

但是loadScan不想工作:

UIImage *imageLoad = [[UIImage alloc] init];
[imageLoad loadScan:[NSString stringWithFormat:@"%@.png", imgName]];
cell.imageScan.image = imageLoad;

我不明白为什么,但文件存在。

由于

1 个答案:

答案 0 :(得分:0)

我找到了一个(奇怪的)方法,但它有效(我发送UIImage也是非参数并在方法中初始化):

- (UIImage *)loadScan:(NSString*)name theImage:(UIImage*)theImg{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [NSString stringWithFormat:@"%@/%@", documentsDirectory, name];
    NSLog(@"loading %@", path);

    [theImg initWithContentsOfFile:path];
    return theImg;
}

致电:

UIImage *imageLoad = [UIImage alloc];
            [imageLoad loadScan:[NSString stringWithFormat:@"%@@2x.png", imgName] theImage:imageLoad];

现在imageLoad有图像数据,我们可以显示它!