I want to save images that user selects from the camera roll, when app exits and restart i want to show those images to user. I have searched over internet and not found much useful resource. I know I can write the image in database as blob but I dont want to do it as increases the database size. Is it possible to save the image path and then later use that path to access that image.
Save the Image into the DocumentDirectory
NSString *imageName = "myImage.png";
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectoryPath = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectoryPath stringByAppendingPathComponent:imageName];
NSData* settingsData = UIImagePNGRepresentation(imageData);
[settingsData writeToFile:dataPath atomically:YES];
EDIT:
If you want to see your saved images on the iPhone/iPad (or share them) in iTunes->Apps->Documents
jut add in Info.plist "Application supports iTunes file sharing" : "YES"
You have to use UIImagePickerController
to get the media from the Camera roll
You will get the image in the delegate method
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
Here you can get the image and save is as NSData .. in a file and then retrieve back it next time
Edit :
to Save
Data = UIImageJPEGRepresentation(theImage,1.0);
NSString *imagePath = [ContentFolder stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.plist",Counter]];
NSLog(#" iamge path %#",imagePath);
NSMutableDictionary *objectDictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:data,#"data", nil];
[objectDictionary writeToFile:imagePath atomically:YES];
you should be able to change these according to your needs..
Related
When my iPhone app runs for the first time it asks you to select an image from your iPhone library to use as the background throughout your app. Here is the relevant code:
/*
* Responds when an image is selected (from browsing)
*/
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
//Not really sure what to do here
UIImage *image = [[UIImage alloc] initWithData:UIImageJPEGRepresentation([info objectForKey:UIImagePickerController], .2)];
}
}
I now what to save this image (or a reference to this image) so that I can use it throughout my app as the background for some (60%) of my UIViewController
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
What is the best/most efficient/easiest way to do this. I thought about saving the image into NSUserDefaults but this didn't seem right because NSUserDefaults is only supposed to be for small objects. Should I save it to disk? But then won't my app be really slow having to read from disk every time I segue? (If this is the proper way, how would I do this?)
Store your Image in Documents Directory
To save Image
- (void)saveImage:(UIImage *)image {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
// Convert to Data
NSData *imageData = UIImagePNGRepresentation(image);
// write to file
[imageData writeToFile:savedImagePath atomically:NO];
}
To read Image use following
- (UIImage *)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
return img;
}
Use a subclassed UIViewController where the background is always this selected background image, which you could have saved off using #Dipen's suggestions below (and +1 to him).
Literally the only thing that needs to exists in your new view controller is that in it's "viewDidLoad:" method, you add a subview that is a "UIImageView", set to your background image which you saved off as some preference.
You can then subclass further view controllers off your new "NosetrapViewController", which will automatically pick up the selected background image.
I am trying to make a simple application using XCode 4.5 which would allow the user to chose any particular image via accessing his photo library, then submit that image for recognition with the help of the Tesseract library.
The problem is that I do not know how to further save the selected user picture, In other words, I can provide the user with an option for going in the picture library and let him chose a picture, but I do not how to then save that selected picture so that it can be further processed.
I hope i made it clear, Appreciate your help.
Try this,
Save image:
NSString *imgName=[#"imgname.png"];
[[NSUserDefaults standardUserDefaults]setValue:imgName forKey:#"imageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imgName];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
Retrive image:
NSString *imgName= [[NSUserDefaults standardUserDefaults]valueForKey:#"imageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:#"%#/%#",documentsDir,imageName];
[imageview setImage:[UIImage imageWithContentsOfFile:filePath]];
What you need to do is save the image data after selection inside the following delegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { You can get the image via the key UIImagePickerControllerOriginalImage in the info dictionary and possibly assign it to an imageview or save it as mentioned by #Kalpesh. Check out apple's documentation for more info. Also check out this good tutorial that shows how to pick photos from the photo album or the camera.
I am still not clear about what exactly you want.
You can always Save Image in or Retrieve Image from Photo Library.
I am creating an iPhone app and in that I want to download multiple image files from web service. And I want to save the images in the local folder in the app itself and save the path to each files in SQLite database. How can I implement this? Please help.
**// Get an image from the URL below**
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"yorimageurl"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
**// Let's save the file into Document folder.**
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#/test.png",Dir];// this path if you want save reference path in sqlite
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegPath = [NSString stringWithFormat:#"%#/test.jpeg",Dir];// this path if you want save reference path in sqlite
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
>> Update Additional:
You need to save image name(unique name that you can do early..right..!!) in sqlite database and you can make path or retrieve image using that name as i shown below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"test.png"];// here you jus need to pass image name that you entered when you stored it.
Hope, this will help you...
After implementing #Nit's code.. you can refer This for insert record in database.
This is showing how to insert record in DB. and for getting path read my comments in #Nit's answer.
UPDATE:
For getting path of each downloaded file you have to keep unique name for each file. Now you will have the path where you are writing file that is unique path for every file. Now you simply need to execute insert query every time you download a file or need to save filepath in array and execute query later according to your requirement. Don't forget to give different file name to every file otherwise only single file will be there and your path will be same.
For getting unique filename you can use timestamp:
NSString *fileName = [NSString stringWithFormat:#"%lf.png", [[NSDate date] timeIntervalSince1970];
UPDATE2:
You have path now like: /Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/84A837AA-7881-4D99-B6E2-623DC9A2E5D3/Documents/test.png
For getting Image in Image view:
UIImage *img = [UIImage imageWithContentsOfFile:yourPath];
//[UIImage imageWithData:[NSData dataWithContentsOfFile:yourPath]];
UIImageView *imgView = // Alloc + Init + Setting frame etc
imgView.image = img;
This will show image in your imageview
Hope this helps
I am attempting to save and load a UIImage to and from the iPhone documents directory after the image is picked from the iPhone Photo Library. It is able to do so, but for some reason, when I load the image, it rotates it 90 degrees counterclockwise. Here is my saveImage and loadImage methods:
Save Image:
- (void)saveImage: (UIImage*)image{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"lePhoto.png"] ];
//NSData* data = UIImagePNGRepresentation(image);
//[data writeToFile:path atomically:YES];
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
}
}
Load Image:
- (NSData*)loadImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"lePhoto.png"] ];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
//UIImage *image = [[UIImage alloc] initWithData:data]; //my second try
//UIImage* image = [UIImage imageWithContentsOfFile:path]; //first try
//return image;
return data;
[data release];
}
And I am now loading the image like this, to see if it would, for some crazy reason, solve my problem (it didn't, obviously):
UIImage* theImage = [[UIImage alloc] initWithData:[self loadImage]];
I have done some testing where I have two UIImageViews side-by-side, one on the left that doesn't save and load the image before display (it just straight-up shows the image once a photo is picked from the ImagePicker), and one on the right that displays AFTER the save load occurs. The one on the right is the only one rotating 90 degrees CCW; the non Save/Load picture is displaying correctly. This only occurs on the actual iPhone. The simulator shows both images correctly. I have spent many, many hours attempting to figure it out, but to no avail. Any ideas as to what could be causing this?
EDIT: It should also be known that the image always says it's oriented up, even when it obviously isn't! It only rotates after ALL of the code has been run. I've tried doing a force redraw in between my code to see if that changes things, but it doesn't (though it is possible I'm even doing that wrong. Who knows, anymore).
Also, it will not autorotate photos that have been screenshot from the iPhone. Only photos that have been taken by the camera. [I haven't tried downloaded photos.] It's the weirdest thing...
And if you're wondering exactly how I'm pulling my picture, here's the method that will at least shed light on what I'm doing (it's not every method needed to do this function, obviously, but it gives insight on how I've written my code):
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
theimageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[self saveImage:[info objectForKey:#"UIImagePickerControllerOriginalImage"]];
[picker dismissModalViewControllerAnimated:YES];
}
Any advice is greatly appreciated. And I do know this much: if there's a way to do something crazy to get some stupid, never-before-heard-of problem, chances are, I'll find it, apparently :P
Ok. I figured it out. Apparently when you save things with PNG representation, and not JPEG representation, the image orientation information is not saved with it. Because of this, every image loaded will default to showing orientation up. So, the easiest way is to do this:
NSData* data = UIImageJPEGRepresentation(image,0.0);
[data writeToFile:path atomically:YES];
instead of this:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
And, of course, changing all the picture names from .png to .jpg. The 0.0 part of the code above is to control Alpha levels, which is required of jpegs. Hope this helps people in the future!
I assume you're using the Assets Library Framework to get the image. If so, you'll want to get the orientation of the image in your results block, and manipulate the UIImage to adjust. I have something like the following:
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset)
{
ALAssetRepresentation* rep = [asset defaultRepresentation];
_orientation = rep.orientation;
...
}
Aside: What a great type name, huh? Holy moly, does Objective-C need namespaces!
Thanks so much...
This code has worked and saved several hours of work for me.
NSData* data = UIImageJPEGRepresentation(image,0.0);
[data writeToFile:path atomically:YES];
in the place of
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
I am simply creating a student management system in iPhone.
There I need to store student's small images,
Which should be appear in tableView,
Ok, I know how to work with tableView...
how to work with database...
But question is
Where to store images
how can we obtain the path of stored images..
Do i have to store entire images to database...
Or
i have to store relative path of image to database...
What is suggested by You masters?
Thanks in advance for helping me.
You can create image files on the file system of the device in the Document directory. Use something like this:
// Generate a unique user filename
NSString *imageFilename = [NSString stringWithFormat:#"student_image_%#", uniqueIdentifier];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
NSData *storage = [image UIImagePNGRepresentation]; // or UIImageJPEGRepresentation
[storage writeToFile:path atomically:NO];
Best Regards,