【问题标题】:Load a saved image from documents directory从文档目录加载保存的图像
【发布时间】:2013-07-06 09:08:21
【问题描述】:

我已经使用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";
}

【问题讨论】:

  • UIImage 实例在 imageWithContentsOfFile 之后是否为零?
  • 似乎问题在于加载后显示 UIImage 而不是加载数据本身。您可以显示您正在使用的代码以便在屏幕上显示它吗?
  • 我已经更新了我的问题.. :)

标签: ios objective-c nsdocument


【解决方案1】:

问题是您仅在 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

【讨论】:

  • 所以让我了解一下情况 - 你从 loadImage 获得一个 UIImage(不是 nil),将它分配给 ImageView(这是一个 IBOutlet 吗?它连接对了吗?)但仍然没有看到图片?
  • 是的...我什至在主队列中添加了这个 ImageName.text = @"dnsdjkvn" 并且文本得到了更新..但图像仍然是空白
  • 尝试在 iOS 模拟器上运行它。导航到 Finder 中的 PNG 资源并查看它。也是空白吗?
  • UIImageView 是如何设置的?任何调整大小的面具?故事板上的自动布局是否有效?尝试设置背景颜色,并在控制器的视图可见后查看它是否可见。延迟加载图像,看看加载后会发生什么
  • 哦...大声笑我在黑色背景上显示黑色图像....但接下来我想通过单击按钮加载下一个图像。一种画廊之类的东西,您可以在其中浏览图像......有什么想法吗??
【解决方案2】:

试试这个

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

它可能会帮助你。

【讨论】:

  • 你能告诉我arrSaveImage是什么吗??
  • 这只是图像名称,我的要求不止一张图像,所以我使用上面的代码并将其放入 for 循环中以一张一张地获取图像
  • 还是一样:'(...我还加了这段代码 NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:strPath error:&error]); 但它给null... 我用@"abcd.png" 替换了 strImageName 和 [arrSaveImage objectAtIndex:i]
  • 您在使用 DocumentDirectory 中的任何文件夹吗?
  • 不......如果我在同一个视图控制器中使用我的代码(在我的问题中提到它),我也会得到图像......但是当我再次从应用程序开始和尝试在新视图控制器中的其他位置加载图像,图像为空白..
猜你喜欢
  • 2012-01-27
  • 2010-11-04
  • 2023-03-25
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多