从文档目录加载已保存的图像

时间:2013-07-06 09:08:21

标签: ios objective-c nsdocument

我使用了here给出的代码来保存和加载图片

当我在一个视图控制器中一起使用它时工作正常,但是当我在一个视图控制器中使用saveImage方法并尝试在另一个视图控制器中加载图像时,图像返回空白...

在视图控制器A中,我使用以下内容保存图像

- (void)saveImage: (UIImage*)image
{
    NSLog(@"saveimage called");

    if (image != nil)
    {
        NSLog(@"Image not null");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          @"test.png" ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
        QrImageView.image = nil;
    }
}

在视图控制器中说B我正在使用..

加载图像
- (UIImage*)loadImage
{
    NSError *error;

    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"test.png" ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];

    // Write out the contents of home directory to console
    NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

    return image;
}

我也在控制台中获取文件的内容,但我不明白为什么图像是空白的

2013-07-06 14:13:19.750 YouBank[500:c07] Documents directory: (
    "test.png"
)

知道我做错了什么......

EDIT:

在viewDidload方法的视图控制器B中,我执行以下操作

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    ImageView.image=[self loadImage];
    ImageName.text = @"Cash Withdrawal";
}

2 个答案:

答案 0 :(得分:6)

问题是你只是在viewDidLoad上用UIImage更新你的UIImageView。一旦从文件系统中获取更新,您需要添加更新(最好是在后台线程上)。所以它看起来像这样:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
    UIImage *loadedImage = [self loadImage];
    dispatch_async(dispatch_get_main_queue(),^{
         ImageView.image = loadedImage;
    });
});

我还建议使用以小写字符开头的名称作为实例名称,因此您应该重命名ImageView - > ImageView的

答案 1 :(得分:1)

试试这个

    //Document Directory
    #define kAppDirectoryPath   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)


    #pragma mark - File Functions - Document/Cache Directory Functions
    -(void)createDocumentDirectory:(NSString*)pStrDirectoryName
    {
        NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL];
    }

    -(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
    {
        NSString *strPath = @"";
        if(pStrPathName)
            strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];

        return strPath;
    }

写你的照片时

        [self createDocumentDirectory:@"MyPhotos"];
        NSString  *pngPath = [NSHomeDirectory()  stringByAppendingPathComponent:strImageName];
        [UIImagePNGRepresentation(imgBg.image) writeToFile:pngPath atomically:YES];

当你收到档案时 的修改

    NSError *error = nil;
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[FunctionManager getDocumentDirectoryPath:@"MyPhotos"] error:&error];
    if (!error) {
           NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"];
       NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
            for (int i=0;i<[imagesOnly count]; i++) {
                [arrSaveImage addObject:[imagesOnly objectAtIndex:i]]; //arrSaveImage is Array of image that fetch one by one image and stored in the array
            }
 }


    NSString *strPath=[self getDocumentDirectoryPath:@"MyPhotos"]; // "MyPhotos" is Your Directory name
    strPath=[NSString stringWithFormat:@"%@/%@",strPath,[arrSaveImage objectAtIndex:i]]; //You can set your image name instead of [arrSaveImage objectAtIndex:i]
    imgBackScroll.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:strPath]];

它可能对你有所帮助。