I'm not quite sure whats going wrong here, I'd really appreciate some help as I'm very stuck.
This is my imagePickerController
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithLong:customphoto1] forKey:#"customphoto1count"];
UIImage *button1Image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
pngData = UIImagePNGRepresentation(button1Image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Button1image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
[self dismissViewControllerAnimated:YES completion:NULL];
pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *imageLoaded = [UIImage imageWithData:pngData];
[_button1 setImage:imageLoaded forState:UIControlStateNormal];
self.button1.clipsToBounds = YES;
self.button1.layer.cornerRadius = (self.button1.frame.size.width / 16);//half of the width
self.button1.layer.borderColor=[UIColor blackColor].CGColor;
self.button1.layer.borderWidth=1.0f;
[self dismissViewControllerAnimated:YES completion:NULL];
}
The above saves the image (as far as I believe) since _button1 is reading from imageLoaded
When the app closes and is reopened, this is the what calls the button to be displayed, and should load the picture from my NSData:
-(void)customButton1{
if (customphoto1 == 1) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Button1image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES];
pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *imageLoaded1 = [UIImage imageWithData:pngData];
NSLog(#"%#", filePath);
// UIImage *imageload1 = [UIImage imageWithData:[newManagedObject valueForKey:#"imagesone"]];
[_button1 setImage:imageLoaded1 forState:UIControlStateNormal];
}
else {
button1ImageName = #"addnew";
}
}
Why is my image not loading?
Many thanks
Try this:
-(void)customButton1{
if (customphoto1 == 1) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Button1image.png"];
UIImage *imageLoaded1 = [UIImage imagewithcontentsoffile:filePath];
NSLog(#"%#", filePath);
[_button1 setImage:imageLoaded1 forState:UIControlStateNormal];
}
else {
button1ImageName = #"addnew";
}
}
Debug: Check whether the filepath which is getting printed is correct or not. Open this path in Finder > CMD + Shift + G and paste the path (remove the file name from the path, use till folder level). Then check if that particular image is available in that folder or not.
Also in your didFinishPickingMediaWithInfo method, you are calling dismissViewControllerAnimated method two times, it should be once and at the end of method.
Hope this helps
Image was saving and loading alright all along - issue turned out to be with the buttons setImage function
Related
I've a question in mind that driving me crazy. I've searched a lot to solve it, but all the answers that I found were old and not helped.
I'm currently working on application with that uses UIImagePickerControllerDelegate and with didFinishPickingMediaWithInfo I want to save the selected image to application folder.
Until now I'm able to select the image with this;
- (IBAction)btnPressed:(UIButton *)sender
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
imgPicker.delegate = self;
imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imgPicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
imgPicker.allowsEditing = NO;
[self presentViewController:imgPicker animated:YES completion:nil];
}
}
but couldn't save it to application using didFinishPickingMediaWithInfo;
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *) kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//Assigning the selected image to imageView to see on UI side.
imageViewerImage.image = image;
}
}
I wonder what should be the part after this point.
I appreciate any help that you can provide.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:NULL];
UIImage* image;
if([[info valueForKey:#"UIImagePickerControllerMediaType"] isEqualToString:#"public.image"])
{
image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *fileName = [stringPath stringByAppendingFormat:#"/image.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:fileName atomically:YES];
}
}
Try this code. It may helps you. :)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
imgViewProfile.image = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:^{ }];
// ------ Now save this image to document directory by getting its path
}
Save an UIImage to the to Documentsfolder like this:
UIImage* myUIImage = ...
NSData *pngData = UIImagePNGRepresentation(myUIImage);
//NSData *pngData = UIImageJPEGRepresentation(myUIImage,0.5); //alternative comressed jpg instead of png
NSString *filePath = [[self buildDocumentsPath] stringByAppendingPathComponent:#"pictureName.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Get the path of the documents as a string:
- (NSString *)buildDocumentsPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return documentsPath;
}
Just save the image in your app document directory :
// first find the path in which to save the image :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *baseDir = [paths objectAtIndex:0];
// then save image as JPEG
NSString* filename = [baseDir stringByAppendingPathComponent:#"filename.jpg"];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
// or PNG
NSString* filename = [baseDir stringByAppendingPathComponent:#"filename.png"];
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
//In Your - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo . Write this code
NSData *pngData = UIImagePNGRepresentation(image);
//This pulls out PNG data of the image you've captured. From here, you can write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
I did that in my project:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage * imageDone = [info objectForKey:#"UIImagePickerControllerEditedImage"];
[self saveImage:imageDone];
[self.popover dismissPopoverAnimated:YES];
}
-(void)saveImage:(UIImage*)image{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * imgpath = [documentsDirectory stringByAppendingFormat:#"/media/img/"];
long x = arc4random() % 10000;
NSString * namePic = [NSString stringWithFormat:#"%lld%ld-photo.jpg", self.idToLoad.longLongValue, x];
NSString * stringName = [NSString stringWithFormat:#"%#%#", imgpath, namePic];
[UIImageJPEGRepresentation(image, 0.3) writeToFile:stringName atomically:YES];
}
In my application I grab an image from a picker and then try to display it in a separate view.
In my MainViewController.m I have
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissViewControllerAnimated:YES completion:^ {
self.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:UIImagePNGRepresentation(self.image) forKey:#"imageKey"];
[defaults synchronize];
PublishViewController *publish = [self.storyboard instantiateViewControllerWithIdentifier:#"Publish"];
[self presentViewController:publish animated:YES completion:nil];
}];
}
I then try to retrieve the image in my PublishViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:#"imageKey"];
UIImage *userImage = [UIImage imageWithData:imageData];
self.image = [[UIImageView alloc] initWithImage:userImage];
}
The image does not show though. Any reason why?
Perhaps your -viewDidLoad in PublishViewController.m is called before the completion block in dismissViewControllerAnimated:completion: and the NSData has not been saved in NSUserDefaults, yet.
You could put the code to load self.image in PublishViewController.m into -ViewDidAppear.
Now that being said I agree with the commenters that NSUserDefaults may not be the best place to store the image data.
Rather than using NSUserDefaults, you are better using NSFileManager to save the image.
Within the pickerController Delegate methods of your MainViewController.m, place the following code -
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
//This code will save your image so you can retrieve it anywhere else within the app.
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentDirectory stringByAppendingPathComponent:#"yourImageName.jpg"];
[manager createFileAtPath:fullPath contents:imageData attributes:nil];
}
Where you can save the image name to whatever you like
Then within the viewDidLoad of your PublishViewController.m place this code to retrieve the image -
-(void)viewDidLoad{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:#"yourImageName.jpg"];
UIImage *retrievedImage = [UIImage imageWithContentsOfFile:fullPath];
self.yourImageView.image = retrievedImage;
}
Place a UIImageView on the view controller of your PublishViewController, which I've called yourImageView, for this example.
This will work for what you're looking for, hope it helps.
Thanks, Jim.
I am making an app that will save a file to the iPhones Documents Directory and then when the View Controller is reloaded it will fetch it from that same location and display it. But it is not fetching it and displaying it.
I am using the following method to save the image:
void UIImageWriteToFile(UIImage *image, NSString *fileName)
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
}
I am trying to recall the image I have saved from the viewDidLoad method with the following code:
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *fileName = [NSString stringWithFormat:#"/%#.png", self.fullname.text];
NSString *filePath = [documentDirectoryPath stringByAppendingString:fileName];
[self.imageView setImage:[UIImage imageNamed: filePath]];
However, it is not showing my image. Can anyone help me and tell me where I am going wrong please. I am new to iOS Development.
replace this line: [self.imageView setImage:[UIImage imageNamed: filePath]];
with this one :
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
[self.imageView setImage:image];
You can use [UIImage imageNamed:] with images from the Documents folder and have the benefits of the underlying caching mechanism, but the file path is slightly different.
Use the following:
NSString *fileName = [NSString stringWithFormat:#"../Documents/%#.png", self.fullname.text];
UIImage *image = [UIImage imageNamed:fileName];
You need to use method
- (UIImage*)initWithContentsOfFile:(NSString*)path
to init images from Documents or Cache directories.
imageNamed: is used for getting images from application bundle.
I am using below code to save and read saved clicked image file from document directory. Its working well for the first time but when i'm trying to read the saved image file for the second time, its showing me the image clicked during first time.
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"test.png" ];
NSFileManager* fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSError* error;
[fileManager removeItemAtPath:path error:&error];
}
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
[self.viewController dismissViewControllerAnimated:YES completion:nil];
}
Any idea why every time its returning me image clicked for the first time.
didFinishPickingImage: is deprecated since iOS3.
This should work:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (!image) {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
if (image) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"test.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
[self.viewController dismissViewControllerAnimated:YES completion:nil];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Please check the documentation.
I have Five buttons.On each button action.I have open gallery and choose an image.But the problem is on each button action same path is coming.
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSData* imageData = UIImagePNGRepresentation(image);
NSString * imageName = #"Myimage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
Set global variable initially int countVal = 1;
NSString * imageName = [NSString stringWithformat:#"%d.png",countVal]; // Imgae_name set here
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
count +=1; // Increment count here
I may be missing something, but it looks like you're using the same name for the image each time: Myimage.png. Every time the image will be saved inside the documents directory with that same name. Maybe add a tag to each button and use that to distinguish each of the 5 different images?
May be it will helpful for u
[picker dismissModalViewControllerAnimated:YES];
imageView.image= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(imageView.image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:png];
[webData writeToFile:localFilePath atomically:YES];
NSLog(#"localFilePath.%#",localFilePath);
UIImage *image = [UIImage imageWithContentsOfFile:localFilePath];
OR
Use this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
imageView.image= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(imageView.image);
[imageData writeToFile:savedImagePath atomically:NO];
NSLog(#"localFilePath.%#",localFilePath);
If you still get it empty then try by checking if NSData is created properly
NSLog(#"webData.%#",webData);
OR
Try this: I hope defnetly it will be be helpful to you
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
//you can use UIImagePickerControllerOriginalImage for the original image
//Now, save the image to your apps temp folder,
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:#"upload-image.tmp"];
NSData *imageData = UIImagePNGRepresentation(img);
//you can also use UIImageJPEGRepresentation(img,1); for jpegs
[imageData writeToFile:path atomically:YES];
//now call your method
[self uploadMyImageToTheWebFromPath:path];
}
Try to use below code which just edited to you answer
The problem is only with saving image name,try to save it with different name
The below code will help you in saving image with diffrent name
note: put the tag value to diffrent button(5 buttons) and call bello method in its target
-(void)saveImage:(UIButton*)sender{
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
NSData* imageData = UIImagePNGRepresentation(image);
NSString * imageName =[NSString stringWithFormat:#"Myimage%d.png",sender.tag];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"fullPathToFile=%#",fullPathToFile); //important line
[imageData writeToFile:fullPathToFile atomically:NO];
}
by this you can save image with different name