Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of saving and loading pictures

I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.

I save most of that profile data with the help of NSUserDefaults, but a friend discouraged me from saving the profile image in NSUserDefault.

What's the proper way to save and retrieve images locally in my app?

like image 335
José Joel. Avatar asked Mar 01 '11 13:03

José Joel.


People also ask

What is the best way to save a picture file?

Right-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want.


1 Answers

You should save it in Documents or Cache folder. Here is how to do it.

Saving into Documents folder:

NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];

BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path 
          contents:nil attributes:nil];

if (!ok) 
{
    NSLog(@"Error creating file %@", path);
} 
else 
{
    NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
   [myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
   [myFileHandle closeFile];
}

Loading from Documents folder:

NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];

You can also use UIImageJPEGRepresentation to save your UIImage as a JPEG file. What's more if you want to save it in Cache directory, use:

[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]
like image 191
Rafa de King Avatar answered Oct 26 '22 21:10

Rafa de King