如何保存此图像数组?

时间:2012-04-11 02:59:51

标签: objective-c ios image tags

我对编程非常陌生,我跳进了一个项目(我知道这不是最聪明的事情,但我正在学习,因为我去了)。我正在编写的应用程序有10个UIImageViews,用于显示用户相机胶卷的图片。我正在使用的代码需要每个UIImageViews都有标签。我目前正在使用NSData来保存数组图像,它工作得很好,但我不能再使用这种方法,因为NSData不支持使用标签。我也不能使用NSUserDefaults,因为我无法将图像保存到plist。以下是我尝试这样做的方法(使用NSData方法,但是我必须编辑它才能使我的标签有效。)

这是我目前的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
    if (imageView.image == nil) {
        imageView.image = img;

        [self.array addObject:imageView.image];

        [picker dismissModalViewControllerAnimated:YES];
        [self.popover dismissPopoverAnimated:YES];
        return;

    }

    if (imageView2.image == nil) {
        imageView2.image = img;
        NSLog(@"The image is a %@", imageView);
        [self.array addObject:imageView2.image];

        [picker dismissModalViewControllerAnimated:YES];
        [self.popover dismissPopoverAnimated:YES];
        return;
    }
    ...


- (void)applicationDidEnterBackground:(UIApplication*)application {
    NSLog(@"Image on didenterbackground: %@", imageView);

    [self.array addObject:imageView.image];
    [self.array addObject:imageView2.image];

    [self.user setObject:self.array forKey:@"images"];
    [user synchronize];

}

- (void)viewDidLoad
{
    self.user = [NSUserDefaults standardUserDefaults];
    NSLog(@"It is %@", self.user);
    self.array = [[self.user objectForKey:@"images"]mutableCopy];
    imageView.image = [[self.array objectAtIndex:0] copy];
    imageView2.image = [[self.array objectAtIndex:1] copy];    

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:app];

    [super viewDidLoad];

}

有关如何编辑此代码的任何帮助或建议,以便我可以保存图像,同时使用标签非常感谢,谢谢!

编辑:这是我更新的代码:

       -(IBAction)saveButtonPressed:(id)sender {
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];

    for (UIImageView *imageView in self.array) {

        NSInteger tag = self.imageView.tag;
        UIImage *image = self.imageView.image;
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];

        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    }
NSLog(@"Saved Button Pressed");
}



- (void)applicationDidEnterBackground:(UIApplication*)application {

}


-(void)viewDidLoad {

    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];

    NSArray *docFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:docsDir error:NULL];

    for (NSString *fileName in docFiles) {

        if ([fileName hasSuffix:@".png"]) {
            NSString *fullPath = [docsDir stringByAppendingPathComponent:fileName];
            UIImage *loadedImage = [UIImage imageWithContentsOfFile:fullPath];

            if (!imageView.image) {
                imageView.image = loadedImage;
            } else {
                imageView2.image = loadedImage;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:4)

您需要使用“快速枚举”来解析数组的对象,并按顺序将每个对象写入磁盘。首先,您需要将UIImageView对象添加到数组而不是UIImageView的UIImage属性,因此您可以恢复标记。所以不要写

[self.array addObject:imageView.image];

将是

[self.array addObject:imageView];

尝试按照我的代码进行操作。我在每一行都插入了评论以提供帮助。

-(void)applicationDidEnterBackground:(UIApplication *)application {
    //Obtain the documents directory
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainmask,YES) objectAtIndex:0];
    //begin fast enumeration
    //this is special to ObjC: it will iterate over any array one object at a time
    //it's easier than using for (i=0;i<array.count;i++)
    for (UIImageView *imageView in self.array) {
        //get the imageView's tag to append to the filename
        NSInteger tag = imageView.tag;
        //get the image from the imageView;
        UIImage *image = imageView.image;
        //create a filename, in this case "ImageTAGNUM.png"
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];
        //concatenate the docsDirectory and the filename
        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    }
}

要从磁盘加载图像,您必须查看viewDidLoad方法

-(void)viewDidLoad {
    //get the contents of the docs directory
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainmask,YES) objectAtIndex:0];
    //Get the list of files from the file manager
    NSArray *docFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:docsDir error:NULL]);
    //use fast enumeration to iterate the list of files searching for .png extensions and load those
    for (NSString *fileName in docFiles) {
        //check to see if the file is a .png file
        if ([fileName hasSuffix:@".png"]) {
            NSString *fullPath = [docsDir stringByAppendingPathComponent:fileName];
            UIImage *loadedImage = [UIImage imageWithContentsOfFile:fullPath];
            //you'll have to sort out how to put these images in their proper place
            if (!imageView1.image) {
                imageView1.image = loadedImage;
            } else {
                imageView2.image = loadedImage;
            }
        }
    }
}

希望这有帮助

您需要注意的一件事是,当应用程序进入后台时,它有大约5秒的时间来清除它的行为,然后才会暂停。 UIPNGRepresentation()函数需要大量时间并且不是即时的。你应该知道这一点。在其他地方编写一些代码可能会比在应用程序后台更早地完成。 FWIW

答案 1 :(得分:1)

您可以使用[NSbundle Mainbundel]存储该图像。

获取路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = [paths objectAtIndex:0];

答案 2 :(得分:1)

首先,你的for循环仍然存在问题。

for (UIImageView *imageView in self.array) {
    NSInteger tag = self.imageView.tag;
    UIImage *image = self.imageView.image;
    // ...
}

在进行任何其他更改之前,您必须了解原因。 imageView是您的 for循环控制变量,它在循环的每次迭代中都会发生变化。 self.imageView是另一回事。它是附加到viewController 的10个imageView中的第一个。每次循环循环时,它会查看第一个imageView,而只查看第一个。

至于为什么保存不起作用,可能是因为其他地方的数组不起作用。添加一些日志记录以确保数组中有某些内容,并且它包含的内容与您期望的一样多。

-(IBAction)saveButtonPressed:(id)sender {
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];

    // Log to make sure the views expected have previously been stored.
    // If the array is empty, or shorter than expected, the problem is elsewhere.
    NSLog(@"Image view array before saving = %@", self.array);

    for (UIImageView *imageViewToSave in self.array) {

        NSInteger tag = imageViewToSave.tag;
        UIImage *image = imageViewToSave.image;
        NSString *imageName = [NSString stringWithFormat:@"Image%i.png",tag];

        NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];

        // Log the image and path being saved.  If either of these are nil, nothing will be written.
        NSLog(@"Saving %@ to %@", image, imagePath);

        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:NO];
    }
    NSLog(@"Save Button Pressed");
}