Load image from photo library without a picker? - ios

Here is what I need.
I need my users to be able to pick an image from the photo library, however, they should not need to have to repick it each time they use it. Instead, I would like to remember the photo's path to be able to load it in the future. Is this possible? If not, what are the alternatives? Is it possible to cache the photo to a local folder or place?
Thanks

You can't keep an reference to the picked image, so you need to, as you suggest your self, save a local copy of the image. You could use the UIImagePicker to let the user pick the image and then save it locally:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage* image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
//save the imageData to document dir. You could also save it to the cache...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *finalPath = [documents stringByAppendingPathComponent:#"myImageName.png"];
[imageData writeToFile:finalPath atomically:YES];
}

Related

How to save and delete image with name in Photo Library in objective c

I am new in iOS and I am facing problem to save image in photo library with name. I am using code like this to save image in photo:
UIImageWriteToSavedPhotosAlbum(Imagename.image, nil, nil, nil);
This code save image in photo library but not with name
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];
NSLog(#"File Path =%#",filePath);
// Save image.
[UIImagePNGRepresentation(Imagename.image) writeToFile:filePath atomically:YES];
This code save image with name but in directory not in photo library.
I need to save image in photo library with name and also need to delete it if it is already save in photo library.

Simulator shows my image in UIImageView but it doesn't on my real iPhone

I have looked around for the answer but it the answers I have found say that real devices are case sensitive and I've looked over my code and cannot find any problems,
I have 2 view controllers, spViewController which is my root and I have secondViewController which is self explanatory, there is an UIImageView in both to display the same image, which was picked from the gallery using UIImagePickerController in the simulator and real iPhone the image DOES display on the spViewController's UIImageView but on the secondViewController in the simulator the UIImageView DOES display the image but on the real iPhone the image DOES NOT display
This code is in my secondViewController.m
{NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepathJPG = [docsPath stringByAppendingPathComponent:#"imagefile.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG];
if (img != nil) {
_imageView.image = img;
BOOL adjustToSmallSize = YES;
CGRect smallSize = (CGRect){0,0,100,100};
if (adjustToSmallSize) {
_imageView.bounds = smallSize;
}
}
I have done a few tests of my own, I've been playing around with the file names and the caps and spellings, if i change the spellings of anything the image fails to load in the simulator also, if i keep it as imagefile.jpg then it loads in the simulator but not the real phone, I've played around with the caps and nothing seems to change on my iPhone or the simulator
Are you sure imagefile.JPG is upper case JPG, or could be imagefile.jpg? Also check what filepathJPG string holds on run time when your imageView fails to load this image file.
check your image name if it is ok than
delete DerivedData at /Library/Developer/Xcode/DerivedData/
and runs once again in the device.
I just look back my old project and this is how I write the image to the fullpath and also get the image back from the same path:-
if (self.photoView.image)
{
//Image file name
NSString *filename = [NSString stringWithFormat:#"M%#.png", self.title];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docDir, filename];
//Write the Image to the path
NSData *imageData = UIImagePNGRepresentation(self.photoView.image);
[imageData writeToFile:fullPath atomically:FALSE];
//Get the image back from the same path
UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
}
I just realised that you forgot the / for the path. Please make sure that whenever you write or read the path, you have that. Can you try it out and let me know if it solves your problem?
To fix my problem i did the following
in my FVC.m
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
//it returns the edited image
NSString *mediaType = info[UIImagePickerControllerMediaType];
self.myImage = chosenImage;
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
if (_newMedia)
{
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
}
}
[self performSelector:#selector(myMethod:) withObject:picker afterDelay:0.5];
}
and then this in my SVC.m
- (void)viewDidLoad
{
[super viewDidLoad];
_imageView.image = self.myImage;
hope this helps people in future

Lost data after store and reload of UIImage in iPhone App

I have developed an iOS7 app. I use the UIImagePickerController to get a UIImage. During the usage of the app an image
is stored to the local app directory and loaded. The file will be overwritten several times. I use UIImagePNGRepresentation and NSData storeToFile to store
the picture. In order to load the image I use UIImage initWithContentsOfFile.
It works fine for some store and load processes. With the Debugger I can confirm that the picture is stored and loaded appropriately.
But after some time the stored picture does not contain a picture anymore. When I look at the load procedure with the debugger I can see that
a picture is loaded but it seems to be completely transparent with no other information.
This phenomenon only occurs on a device and not during a simulation with the simulator. Furthermore, the effect seems to occur only when the app is kicked out of the memory (double tap of the home button)
I debugged the app for hours but I cannot imagine the reasons for this behaviour. Additionally it is difficult to debug due to the complete termination of the app. Does anybody know a solution or has been faced with the same problem? Could anybody give me a hint what to debug to track down the problem?
Thanks in advance. Any help is appreciated. :)
Thanks for your answers. Here is a code excerpt:
Code to store image:
Generate file path in documents directory
NSString *name = [NSString stringWithFormat:#"ImageforButton%i.png",i];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [[path objectAtIndex:0] stringByAppendingPathComponent:name];
Create NSData from UIImage (image is a UIImage that always has the correct image data)
NSData *picData = UIImagePNGRepresentation(image);
Write NSData to file
[picData writeToFile:file atomically:true];
Code to load image:
Generate file path
NSString *name = [NSString stringWithFormat:#"ImageforButton%i.png",i];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [[path objectAtIndex:0] stringByAppendingPathComponent:name];
Load picture
UIImage *img;
if ([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:false] == true)
{
img = [UIImage imageWithContentsOfFile:[self saveFilePath:name]];
}
img does not always contain the right data. Before the app is completely terminated img
contains the expected picture. After the app was completely terminated a valid
UIImage can be loaded to img but it seems only to contain a transparent picture.
All in all it does not contain the right picture anymore.

Save image path to sqlite3 database

I am having some troubles saving images path into Documents folder and store the path into my sqlite3 local db.
Today I successfully stored the images as BLOB into the db, but reading around the Internet, people said that this is not recommended.
So, now I'm trying to store image path in DB but..
Situation
User taps a button to choose an image (via UIImagePickerView) or take a new photo
After choosing the image, an imageView is set with the image chosen.
Code for picker:
-(void)imagePickerController:(UIImagePickerController *)pickr didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
/* Test code for saving data */
//NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//NSString *pngPath = [NSString stringWithFormat:#"%#/test.png",dir];
//NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
//[data writeToFile:pngPath atomically:YES];
[imageView setImage:image];
picture = YES;
[pickr dismissModalViewControllerAnimated:YES];
}
Now I got a couple of questions
Into my db, image is BLOB type. Should I edit it to TEXT?
How is the path saved? I mean, in the test code /test.png is a generic image name. Does the chosen image name get saved too so that I can retrieve it? Or, better, if I save an image picked from my library with name "IMG0001", does it get saved as "test"?
What's the right way to save an image into documents folder, its path to the DB and then retrieve it?
I googled a lot to find an answer, but after experimenting a lot I gave up.
Thanks in advance
Here is nice tutorial on how to save images in Documents directory
You need to convert your BLOB field to TEXT field and just save file name of that image. You can also create folder in Documents directory and then access by foldername/filename.png.
Hope this information helps you..
EDIT
Here is code to check if that folder exits, If not exist create new that folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if( [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
;// success
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
}
You cannot directly access the image from the user's photo library, since you have access only to your Applications Sandbox folder.
So if you don't want to store the image as a blob file in the database, you should save the image in the caches folder inside your App's documents folder and then store the filename you set to the image in the database.
Since all images are going to be in the same path folder, you don't need to actually save the entire path in the database, but only the filename should be sufficient enough.

How to save a new-token photo in IOS

I'm now struggling with UIImagePicker.
I've read the document but it seems not to mention how should I save a newly token photo, I mean save it into my own documents in my app.
In fact, there is a "photo" attribute in one of my entity in core data,
so, the "photo" should just be a NSString to save the real photo's file path, right?
But how to save that photo and get its correct file path?
I just know little about NSFilePath or something like that, hope someone to teach me a little bit.
Thanks a lot!
You may know how to present the image picker:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[viewController presentModalViewController:picker animated:YES];
With the above the viewController implements the UIImagePickerControllerDelegate and make sure you implement this function:
- (void)imagePickerController:(UIImagePickerController *)returnedPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
and
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)returnedPicker
The first method is called when user has picked a photo. In this method you get the image using:
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
To write this to a file you can make it a JPEG or a PNG. If a JPEG you may do this:
[UIImageJPEGRepresentation(image, 1.0) writeToFile:filename atomically:YES];
You just need to set the filename.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [paths objectAtIndex:0];
NSString *filename = [docsDir stringByAppendingPathComponent:#"myFilename.jpg"];
To get the image back into a UIImage you do this:
NSData *data = [NSData dataWithContentsOfFile:filename;
if(data != nil)
UIImage *image = [UIImage imageWithData:data];

Resources