NSDocumentDirectory legal to save and load images on device? - ios

The following code works on the simulator but crashes the device because img is nil:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (NSString* path in userImages) {
NSLog(#"image at %#", path); //logs "image at userImage0.png"
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:path];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
unichar ch = [path characterAtIndex:9];
NSLog(#"Ch = %c", ch); //correctly logs "0"
if (ch == '0') {
[self.images insertObject:img atIndex:0]; //this throws the error
}
}
Why is img nil when run on the device but not on the simulator? The image is originally saved like this:
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *imageName = #"userimage0.png";
NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
[UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];

Sorry, it was a capitalization problem. userimage vs userImage. The simulator doesn't care about that (I wish it did), but the device does.

Related

Data is nil from image string.

It is my save method :
-(NSString *)saveImage:(UIImage *)image
{
NSInteger RandomIndex = arc4random() % 1000;
NSString *randomImageName =[NSString stringWithFormat:#"Image%i.png",RandomIndex];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:randomImageName];
if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
[[NSFileManager defaultManager] removeItemAtPath:savedImagePath error:nil];
NSLog(#"file removed from path");
}
NSLog(#"Saved Image Path : %#",savedImagePath);
NSData* imageData = UIImagePNGRepresentation (image);
[imageData writeToFile:savedImagePath atomically:YES];
self.teamLogo = savedImagePath;
return savedImagePath;
}
I try to load image and put into control :
NSData *myData = [NSData dataWithContentsOfFile:self.team.logo];
UIImage *selectedImage = [UIImage imageWithData:myData];
self.team.logo is from DB. I keep string in base. In debug mode i got this string :
/var/mobile/Containers/Data/Application/7CD69EC9-9C20-48EE-B611-FC2353BC31B0/Documents/Image364.png
and myData is still nil. Do you have idea why ?
Starting from IOS 8 layout of containers changed. So don't store full path to your DB. Instead just store your image name. For recalling the image use:
NSString *temp = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"Image364.png"];
NSData *myData = [NSData dataWithContentsOfFile:temp];
UIImage *selectedImage = [UIImage imageWithData:myData];
I hope it helps.

Save and load UIImageView

I want to save and load image in UIImageView
I have already tried some code but it doesn't work.
The Code i have tried:
Save:
UIImage *image = ...;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];
Load:
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];
But these code doesn't work!
I hope you want to save image in document directory folder
here is the way to 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: #"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
to get image from document directory:
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Hope this will help
Globally declare imageView
UIImageView *imageView;//if u create imageView in interfaceBuilder. then u can replace this line by creating outlet of ur imageView
for loading image:
//Loading image in imageView
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachedImagePath])
{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];
if (image)
{
imageView = [[UIImageView alloc]init];//Dont do this, if u created imageView using interFace builder
[imageView setFrame:CGRectMake(50, 100, 200, 200)];//Dont do this, if u created imageView using interFace builder
[self.view addSubview:imageView];//Dont do this, if u created imageView using interFace builder
[imageView setImage:image];
}
else
{
NSLog(#"Unsupported File");
}
}
else
{
NSLog(#"Image not Found in the path");
}
for saving image:
UIImage *image = imageView.image;
if (image)
{
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"imageSaved.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachedImagePath])
{
NSLog(#"File Created");
}
}
else
{
NSLog(#"No image to save");
}

How to get path of the image choose from gallery in iPhone?

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

How can I add more images in NSDocumentDirectory?

First I stored image path from web service into SQLITE, and then I retrieve it back using local path. I am using NSMutableArray. I've successfully stored one image in NSDocumentDirectory, but I have one issue, How can I store more than one images in NSDocumentDirectory?
My code is,
if ([[[node childAtIndex:counter] name] isEqualToString:#"Column5"])
{
NSString *str = [[node childAtIndex:counter] stringValue];
[Col5 addObject:str];
NSString *myString = [Col5 componentsJoinedByString:#","];
NSString *aString = [NSString stringWithFormat:#"http://webserviceurl/%#",myString];
NSURL *url= [NSURL URLWithString:aString];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strCol4];
UIImage *image = tmpImage;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
For this line:
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strCol4];
Just use a different path component.

How to set button background from iphone documents folder

I have image file which is stored in the iphone documents dir when i gave that image to button background it does not show.
NSString*imageThumbnailVideo= [NSString stringWithFormat:#"%#thumbVideo.png",imageThumbnail];
NSLog(#"imageThumbnailVide is %#",imageThumbnailVideo);
NSString * filePath = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(),imageThumbnailVideo];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists == 0)
{
NSLog(#"File is Not exists");
}
else
{
NSLog(#"File is present");
}
[thumbnailImageView setBackgroundImage:[UIImage imageNamed:imageThumbnailVideo] forState:UIControlStateNormal];
It also shows File is Present but does not display image.
Here is how i am saving the file
testT=[NSString stringWithFormat:#"%#thumbVideo",titleTextField.text];
NSString *newStringVT = [testT stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString*imageTitleVT=[NSString stringWithFormat:#"%#.png",newStringVT];
NSString *pathVT = [documentsDirectory stringByAppendingPathComponent:imageTitleVT];
NSData*thumbVideoData=UIImagePNGRepresentation(thumbnail);
NSError * error = nil;
[thumbVideoData writeToFile:pathVT options:NSDataWritingAtomic error:&error];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *img_path = [documentsDirectory stringByAppendingPathComponent:#"YOUR IMAGE NAME.png"];
NSURL* uurl=[NSURL fileURLWithPath:img_path];
[thumbnailImageView setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:uurl]] forState:UIControlStateNormal];
You can obtain the image from a file by doing something like this:
UIImage* anImage = [UIImage imageWithContentsOfFile:validFilePath];
and then you can apply that image to a button like this:
[_someButton setImage:anImage forState:UIControlStateNormal];

Resources