Saving and loading UIImage in an iPhone app - iphone

I am having a headache working out what's wrong with my app. I am trying to save and load UIImages, simple right? Seems not so.
I have a class with these methods to save, load and delete an image with a unique string. Just how I like it, nice and simple. Here is the class:
imageSavedLoad.h:
#import <Foundation/Foundation.h>
#interface imageSaveLoad : NSObject
- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName;
- (void)removeImage:(NSString*)fileName;
- (UIImage*)loadImage:(NSString*)imageName;
#end
imageSaveLoad.m:
#import "imageSaveLoad.h"
#implementation imageSaveLoad
//saving an image
- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName
{
NSData *imageData = UIImagePNGRepresentation(image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]];
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
NSLog(#"image saved");
}
//removing an image
- (void)removeImage:(NSString*)fileName
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
//loading an image
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
#end
Where I want to save, load or delete an image I import the class: #import "imageSaveLoad.h"
Then I create an instance of it and call the required methods (here I save):
imageSaveLoad *imgSL = [[imageSaveLoad alloc] init];
[imgSL saveImage:photoImgView.image forKey:#"yourPhoto"];
Then in another view/class where I want to retrieve the image:
imageSaveLoad *imgSL = [[imageSaveLoad alloc] init];
yourImgView.image = [imgSL loadImage:#"yourPhoto"];
But yourImgView displays nothing, blank.
So where am I going wrong? I have checked all IBOutlet connections and that all the code is being called. Is there a problem with the methods I am using?

When saving image, try by replacing this line :
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
With
[imageData writeToFile:fullpath atomically:YES];

Related

How to copy one image and save as diff. name in document directory

In my document directory one image is their, with name Image1.
I want copy same image with name Image2 in document directory folder.
Please, suggest me how can i do that?
refer a following code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *imagePath1= [documentDirectory stringByAppendingPathComponent:#"image1.png"];
NSString *imagePath2= [documentDirectory stringByAppendingPathComponent:#"image2.png"];
[[NSFileManager defaultManager] copyItemAtPath:imagePath1 toPath:imagePath2 error:nil];
Get he data from first image and save the same data with another name like:
NSData *data = UIImageJPEGRepresentation(image1, 1.0);
NSString *str=#"image2.png"
NSString *fileName = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:str];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[data writeToFile:fileName atomically:YES];
I have two mathed of Fatch image and save image:
You fatch image that save in Document directory and then pass it to save image with different name:
-(UIImage *)loadImage:(NSString *)name
{
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *res = [UIImage imageWithContentsOfFile:fullPath];
return res;
}
-(void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSData *data = UIImageJPEGRepresentation(image, 1);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}

can't creating plist file in document folder

I have write code like this in Viewdidload method. But it don't create file .plist.
I don't know whether code is wi8 or wrong. And where i have to write?
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data1.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( ![fileManager fileExistsAtPath:path] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"data1" ofType:#"plist"];
}
You have just created a path to it, you should try loading it into a NSDictionary.
NSDictionary* mydictionary = [ NSDictionary dictionaryWithContentsOfFile: pathToSettingsInBundle];
Inside your if block add a second line
[fileManager copyItemAtPath:pathToSettingsInBundle toPath:path error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
plistpath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:#"Product.plist"]];
And then
[array writeToFile:path atomically:YES];
[Whatever [Array or Dictionary] you want to Write in Plist]
If it is still not creating the plist then check whether your array or dictionary must be empty.

writing to plist but it's empty when I quit simulation

Hi I implemented this object PlistManager to write/read plist in my project.The problem is that the plist is populated fine will running (I hope) and when entering in background (I used notification and NSlog the [Plistmanager readPlist:#"Database"]) i still can read the data entered before.
The point is when I stop the simulation on xcode and run again the plist is now empty. Why?
#interface ReadWritePlist : NSObject
+(void)writeToPlist:(NSString*)filePlist dic:(NSDictionary*)dic;
+ (NSMutableDictionary *)readPlist:(NSString*)filePlist;
#end
#implementation ReadWritePlist
+ (void)writeToPlist:(NSString*)filePlist dic:(NSDictionary*)dic
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[dic writeToFile:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",filePlist]] atomically:YES];
}
+ (NSMutableDictionary *)readPlist:(NSString*)filePlist {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:filePlist] stringByAppendingPathExtension:#"plist"];
NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
return dic;
}
solved
I just found these new methods for read/write plist and it is working.I had to add the "initializeFileDic" method inside appdelegate (didFinishLaunchingWithOptions):
#implementation PlistManager
+ (NSMutableDictionary *)readPlist:(NSString*)filePlist {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:filePlist] stringByAppendingPathExtension:#"plist"];
NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
return dic;
}
+ (void)writeToPlist:(NSString*)filePlist dic:(NSDictionary*)dic
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if ([dic writeToFile:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",filePlist]] atomically:YES]) {
NSLog(#"Ok done!");
}
else{
NSLog(#"Noo not done!");
}
}
+ (void)initializeFileDic:(NSString*)FileNameExt
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *startPath = [[path stringByAppendingPathComponent:FileNameExt]stringByAppendingPathExtension:#"plist"] ;
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[documentsDirectoryPath stringByAppendingPathComponent:FileNameExt]stringByAppendingPathExtension:#"plist"];
NSLog(#"%# \n,\n %# ",startPath,filePath);
if([NSDictionary dictionaryWithContentsOfFile: startPath]){
NSLog(#"File %# exists",filePath);
}
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
if([[NSDictionary dictionaryWithContentsOfFile:startPath] writeToFile:filePath atomically:NO])
NSLog(#"File copied inside App DocumentsDirectory\n\n");
else
NSLog(#"Error while trying to copy into DocumentsDirectory\n\n");
}
}
#end
Could Anybody explain what was wrong?
Thanks
When do you make the call to save the data to the plist? If you quit your app from Xcode then it is terminated immediately, and doesn't go through any of the application delegate methods related to terminating or entering the background, which is where I suspect your code is.
Pressing the home button on the simulator is the way to get those methods to run.

iPhone Load and Save Multiple UIImages with Unique Key?

I know there are some solutions out there for saving and loading images on your iPhone. However none have quite worked for me.
For example, the link below has a great code chunk which lets you load and save a UIImage with a unique key, but I can't work out how to tell when loading an image using this code if an image under that key already exists or not.
http://www.friendlydeveloper.com/2010/02/using-nsfilemanager-to-save-an-image-to-or-loadremove-an-image-from-documents-directory-coding/
//saving an image
- (void)saveImage:(UIImage*)image:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
//removing an image
- (void)removeImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
//loading an image
- (UIImage*)loadImage:(NSString*)imageName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
If you could help me work out that out it would be really appreciated. I need to save several images, and load them depending on if a given key already exists or not.
if u want to get images with unique key, try using UUID. This will always give u image with unique key..For example here is an example of using UUID..
- (NSString *)pathForImageFileWithPrefix:(NSString *)Prefix
{
CFUUIDRef uuid;
CFStringRef uuidStr;
uuid = CFUUIDCreate(NULL);
uuidStr = CFUUIDCreateString(NULL, uuid);
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1.0);
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
result = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_%#.png",Prefix, uuidStr]];
[imageData writeToFile:result atomically:NO];
CFRelease(uuidStr);
CFRelease(uuid);
return result;
}
If I get your question right, you want to know whether a file with the given image name already exists? Then you can just use
bool fileExists = [NSFileManager defaultManager] fileExistsAtPath:filePath];

Save Image on iPhone idle time

I want to save the loaded image from server in idle time.I use the following to to save image in iPhone memory.
- (void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSData *data1 = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data1 attributes:nil];
if (image==nil) {
NSLog(#"Not Saved...:%#",name);
}
}
but when his method called i got halt time....i don't want that...i want to save image when iPhone is inactive.....can help??
Thanks
You need to do this in the background, using a thread.
If you're supporting iOS 4.0 only, it's really easy:
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
NSData *data1 = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data1 attributes:nil];
if (image==nil) {
NSLog(#"Not Saved...:%#",name);
}
});
}
Otherwise, look up the NSThread documentation, or performSelectorInBackground:withObject:.