Delete an image in NSDocumentDirectory - iphone

I have a custom library that can pick mulitple images from the camera roll, I save my images in the NSDocumentDirectory like this:
for (int i = 0; i < info.count; i++) {
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
NSLog(#"saving at:%#",savedImagePath);
}
What I wanted to do is I wanted to load it in a thumbnail with UIScrollView then when a specific picture is tapped a AlertView will popup,will ask the user if it wants to delete it. I manage to make it load in a thumbnail view (I use theHSImageSidebarView) and make the AlertVIew popups whenever a user taps in a image. But when I press delete it deletes in the view but not in the NSDocumentDirectory.
This is how I delete my image:
- (void)sidebar:(HSImageSidebarView *)sidebar didRemoveImageAtIndex:(NSUInteger)anIndex {
NSLog(#"Image at index %d removed", anIndex);
[images removeObjectAtIndex:anIndex];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", anIndex]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}

On this line, replace %d with %lu
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", anIndex]];

Related

how to display image from documents folder in of iphone to image ViewI [duplicate]

This question already has answers here:
Loading an Image from documents directory
(6 answers)
Closed 9 years ago.
I want to display image saved in the documents folder problem is that it returns file name but it does not show image in the image View
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString*patientlastName;
NSString*test=#"nicej";
patientlastName=[test stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString * filePath = [NSString stringWithFormat:#"%#/Documents//%#.png", NSHomeDirectory(),patientlastName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists == 0)
{
NSLog(#"File is Not exists");
appDelegate.imageURL=#"File Not Exists";
}
NSString *userfile=[NSString stringWithFormat:#"%#",patientlastName];
appDelegate.imageURL=userfile;
PictureDisplayViewController *targetController = [[PictureDisplayViewController alloc] initWithNibName:#"PictureDisplayViewController" bundle:nil];
targetController.modalPresentationStyle = UIModalPresentationFullScreen;
[self.splitViewController presentViewController:targetController animated:YES completion:nil];
In PictureDisplayViewController
imageView.image=[UIImage imageNamed:#"nicej.png"];
try this code:
save image in this path:
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *str= [NSString stringWithFormat:#"%#.png",patientlastName];
NSString *Image_filePath=[documentsDirectory stringByAppendingPathComponent:str];
NSData *imagedata=UIImagePNGRepresentation(yourimage);
[fileMan createFileAtPath:[Image_filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] contents:imagedata attributes:nil];
get image path:
NSString* fileName = [NSString stringWithFormat:#"%#.png",patientlastName}
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *path = [arrayPaths objectAtIndex:0];
NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
UIImage *image1=[UIImage imageWithContentsOfFile:pdfFileName];
imageView.image=image1;
//suppose imgpath is path of your image in doument directory then use these two lines of code.
NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
imageView.image = [[UIImage alloc] initWithData:imgData];
In PictureDisplayViewController, you are loading image with imageNamed method that actually doesn't work until you have image with the same name into your bundle.
you can load image like as follow...
In PictureDisplayViewController you already have path for the image than
imageView.image= [UIImage imageWithContentsOfFile:filePathWithName];
I modify your code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString*patientlastName;
NSString*test=#"nicej";
patientlastName=[test stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString * filePath = [NSString stringWithFormat:#"%#/Documents//%#.png", NSHomeDirectory(),patientlastName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists == 0)
{
NSLog(#"File is Not exists");
appDelegate.imagePath=#"";
}
else
{
appDelegate.imagePath=filePath;
}
PictureDisplayViewController *targetController = [[PictureDisplayViewController alloc] initWithNibName:#"PictureDisplayViewController" bundle:nil];
targetController.modalPresentationStyle = UIModalPresentationFullScreen;
[self.splitViewController presentViewController:targetController animated:YES completion:nil];
In PictureDisplayViewController
if(appDelegate.imagePath)
{
UIImage *image=[UIImage imageWithContentsOfFile:appDelegate.imagePath];
}
else
{
imageView.image=[UIImage imageNamed:#"default.png"];
}
default.png is a default png pic in your bundle resource

Retrieve multiple images from document directory

I have folder named "2" in document directory. Now in folder "2", I have five images named 0.png, 1.png, 2.png, 3.png and 4.png. I want to retrieve these images and save into an array. I have code but it returns only one image.
int b=2;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d/0.png",b]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
NSLog(#"%#",getImagePath);
imge.image=img;
Just use NSFileManager, something like this:
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
It will give you an array with all the file paths for all files in the given path.
This is how you load the images from the array of URLs.
NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
for (NSURL *url in paths)
{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}
You should loop through the images.
int b=2;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:5];
for (int i = 0; i < 5; i++)
{
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d/%d.png",b, i]];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
[images addObject:img];
NSLog(#"%#",getImagePath);
imge.image=img;
}
Instead of hardcoding the count and names of the image files, as Dominik suggested you should use contentsOfDirectoryAtPath:error: to get the list of files in that directory.
NSError *error = nil;
NSArray *imageFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d",b]] error:&error];

Save images to NSLibraryDirectory in a particular folder

I want to save the images in NSLibraryDirectory, the code i am using is replacing image, when next image is saved.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"images.doc"];
UIImage *image = [arrayImages objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
NSMutableArray *imag = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"1333681269.jpeg"],[UIImage imageNamed:#"image001-794043.jpeg"],[UIImage imageNamed:#"Circle.png"], nil];
for(int i=0;i<[imag count];i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [NSString stringWithFormat:#"savedImage%i.png",i];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSData *imageData = UIImagePNGRepresentation([imag objectAtIndex:i]);
[imageData writeToFile:savedImagePath atomically:NO];
}
Each time you have to use a different name that isn't already used.So You have to change the file name Each time.
If you want work it even after app restarted ,Save the index value to NSUserDefaults
.h file
int index;
Change your code as in .m
index = [[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"NewFolder"];
NSString *dynamicimagename = [[#"/images" stringByAppendingFormat:#"%d",[[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"]] stringByAppendingFormat:#".doc"];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:dynamicimagename];
UIImage *image = [arrayImages objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(image);
BOOL isWritten = [imageData writeToFile:savedImagePath atomically:NO];
index++;
[[NSUserDefaults standardUserDefaults] setInteger:index forKey:#"HighScore"];

How to copy one image and save as diff. name in document directory

In my document directory one image is their, with name Image1.
I want copy same image with name Image2 in document directory folder.
Please, suggest me how can i do that?
refer a following code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *imagePath1= [documentDirectory stringByAppendingPathComponent:#"image1.png"];
NSString *imagePath2= [documentDirectory stringByAppendingPathComponent:#"image2.png"];
[[NSFileManager defaultManager] copyItemAtPath:imagePath1 toPath:imagePath2 error:nil];
Get he data from first image and save the same data with another name like:
NSData *data = UIImageJPEGRepresentation(image1, 1.0);
NSString *str=#"image2.png"
NSString *fileName = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:str];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[data writeToFile:fileName atomically:YES];
I have two mathed of Fatch image and save image:
You fatch image that save in Document directory and then pass it to save image with different name:
-(UIImage *)loadImage:(NSString *)name
{
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *res = [UIImage imageWithContentsOfFile:fullPath];
return res;
}
-(void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSData *data = UIImageJPEGRepresentation(image, 1);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}

Iphone : How to Display Document Directory images in Image View?

In a App images stored in Document Directory Folder,
I wanted Particular image display in Image view,
How that image Display in Image View from the Document Directory ?
sample code:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(void)loadimage{
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"your image-name"];
UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubView:myimage];
[myimage release];
}
TNQ
You can achieve it, By knowing the names of your images, so while you are storing your image you need to store some information of these images in database,(or some where you can use it), then fetch name of image from data source, and work as follows:
NSString *str = [NSString stringWithFormat:#"%#.jpg",[myGlobleArrayOfImageNames objectAtIndex:imageCounter]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullImgNm=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:str]];
[mainSlideShowImageView setImage:[UIImage imageWithContentsOfFile:fullImgNm]];
Here you can take UIImageView in your View and add it to the view and do the same like as follows:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageFilePath;
NSError *err;
imageFilePath = [documentsDirectory stringByAppendingPathComponent:#"image1.png"];
UIImageView *objImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
objImageView.image = [UIImage imageWithContentsOfFile: imageFilePath];
[self.view addSubVIew:objImageView.image];
[objImageView release];
Please let me know if you still need any help.
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
imagePath= [imagePath stringByAppendingPathComponent:#"imagename.png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *img = = [UIImage imageWithData:data];
you can display this image to uiimageview
you need following lines of code to get UIImage from documents directory
-(UIImage*)getImage:(NSString *)strImageName
{
NSString *documentDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imagePath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",strImageName]];
UIImage *image=[UIImage imageWithContentsOfFile:imagePath];
return image;
}
Call above function and use UIImage object to set anywhere you want.
You can also write this method in a common class to use it anywhere.
Adding to these answers I find its good practice to check if the file exists like so...
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *file = [directory stringByAppendingPathComponent#"my_image.jpg"];
if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
self.myimageview = [UIImage imageWithData:[NSData dataWithContentsOfFile: file]];
}
Simple Use This Code
NSFileManager *filemgr =[NSFileManager defaultManager];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *dataPath = [docsDir stringByAppendingPathComponent:#"/yourdirectory/image.jpg"];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:dataPath]];
self.imageview.image = [[UIImage alloc] initWithData:imgData];