Saving an Mutable array of images and loading them

送分小仙女□ 提交于 2020-01-07 04:40:41

问题


I have part of my app that will take a photo and the person can elect to save it i then save the image to an array but what ways can I save it to the phone WITHOUT it being put in the photo library. I tried

UIImage *image = imageView1.image;

[array addObject: image];

NSUserDefaults *default = [NSUserDefault standardDefaults];
[defaults setObject:image withKey:@"saved image"]; //not exact code just showing the method 

I use to save the array of images

[defaults synchronize];

then i also use UserDefaults to load array but it does not work. I am wondering if there is a different way to save images without saving them to the photo library.


回答1:


In principle, you could save the images in NSUserDefaults using

[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) 
                                          forKey:key];

But keep in mind that NSUserDefaults is meant for storage of preferences, not images. You better save the images in the documents folder and store the path in NSUserDefaults (as suggested by Wain).




回答2:


You cannot save images the way you want. In your case, array contains just pointers to the images, not images itself. So, one way around is, as @Wain suggested, writing image to the disk, and add path of the saved image to the array, and then saving that array to the NSUserDefaults. You can save image to the disk by converting it to the NSData, and writing it in Documents or tmp folders of application sandbox. In order to convert image to the NSData, you could use UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality) method, and in order to write data to the disk, use writeToFile:atomically method of NSData.

Good Luck!




回答3:


You can save them into the Document directory:

NSData *imageData = UIImagePNGRepresentation(imageView1.image);
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/imageName.png"];
[imageData writeToFile:imagePath atomically:YES];

And save their URLs in NSUserDefaults:

NSUserDefaults *default = [NSUserDefault standardDefaults];
[defaults setObject:imagePath  withKey:@"saved image "];
[defaults synchronize];

And simply retrieve image:

UIImage *customImage = [UIImage imageWithContentsOfFile:imagePath];


来源:https://stackoverflow.com/questions/20237198/saving-an-mutable-array-of-images-and-loading-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!