【问题标题】:Saving images to a directory将图像保存到目录
【发布时间】:2012-08-13 09:28:27
【问题描述】:

您好,我想将图像保存到目录中,我传递 NSData 并执行我认为会将文件保存在我创建的目录中的操作,但问题是它不保存。这就是我到目前为止所拥有的。为什么initWithContentsOfURL:encoding:error: 不起作用,它返回 null 但我使用的另一种方法起作用?主要问题是 WRITETOURL 返回一个 0 我认为这意味着信息没有正确存储,有什么提示吗?

     NSFileManager *fm = [[NSFileManager alloc] init];
        NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
        NSLog(@"%@", directoryPaths);
        NSURL* dirPath = nil;    
        dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:@"photos.jpeg"]];
       NSError* theError = nil;
       [fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];

    UIImage* photoToStore = [UIImage imageWithData:photoToSave];

    NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:@"%@.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)];
    NSError *error = nil;


    BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    NSLog(@"OK = %d", OK); //Returns 0
    NSLog(@"%@", dirPath);

    //WHY DOESNT THIS VERSION WORK?
    // NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"%@", pathToFile);

      NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil];
    NSLog(@"%@", dirContents);

【问题讨论】:

    标签: objective-c xcode nsstring nsurl nsfilemanager


    【解决方案1】:

    在 .h 文件中这样做和 int count 并设置其初始值 count = 0;在 viewDidLoad 中:

    NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@"Image_%d.png",count];
    error = nil;
    if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts
    {
       [[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error];
    }
    
    if(photoToSave) // nsdata of image that u have
    {
      [photoToSave writeToFile:stringPath atomically:YES];
    }
    count++; // maintaining count of images
    

    【讨论】:

    • 它还声称 NSData 没有声明 WRiteToFile?
    • 另外,如果我将多张图片保存在一个文件中,如何获取特定数据的内容?
    • 检查已编辑的答案,我不明白将多个图像保存在一个文件中的想法(就像一个 pdf 中的所有图像)
    猜你喜欢
    • 2015-07-04
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多