I am using photo library in my app. And after selecting image from photo library or camera i want to save that image into my Documents folder. So here i want to give name to that image while saving is it possible to set name to the selected image? If means please let me know. I am trying that only if possible i will post that.Thank you.
This is how I do it.. I'm copying and pasting my code so there's some additional functionality.
// image is a UIImage
// inputText is the user selected imagename
// date is a string I inserting to make pictures a unique identifier (i.e. no duplicate names)
NSData *imageData1 = UIImageJPEGRepresentation(image, 1.0);
NSString *imageFilename = [NSString stringWithFormat:#"%#-%#.jpg", inputText,date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
if([imageData1 writeToFile:path atomically:YES]){
NSLog(#"Write to Document folder success filename = %#",path);
}
Use following :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *photoImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/myImageName.png"];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];
if(status){
[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];
}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}
You can set any desired name when saving to document directory.
Declare an integer counterNo and initialize it to 0. And increase its value to change name dynamically.
UIImage *photoImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
counterNo++;
NSString *aaa = [NSString stringWithFormat:#"Documents/myImage-%d.png" , counterNo];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:aaa];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];
if(status){
[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];
}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
Related
It would seem that my apps no longer are able to save files to their documents folder when doing this:
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
NSLog(#"writing file: %#", path);
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
I do get "Written" in the log with the full path:
Written: /var/mobile/Containers/Data/Application/ECBCD65D-A990-4758-A07F-ECE48E269278/Documents/9d440408-4758-4219-9c9c-12fe69cf82f2_pdf.pdf
And as long as I don't quit the app I can load the PDF in a UIWebView like this (pdfPath is a string that I pass to the function that loads the PDF file):
[www loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]]];
Any help at all is as always greatly appreciated.
Okay, after mucking about I found that since the documents directory changes path every time I run the app, I had to:
Write the file to the documents folder with the complete path to
the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
Save only the file name to my database
Load the file by using the full newly generated Documents directory path and append the file name from my database:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: pdfPath];
Is there a way to disable the "Saved Photos" folder when saving an image?
NSData *data1 = UIImagePNGRepresentation(imageToCrop.image);
UIImage *tehnewimage = [UIImage imageWithData: data1];
[self.library saveImage:tehnewimage toAlbum:#"Databender Edits" withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"eRrOr: %#", [error description]);
}
}];
If you are using ALAssetsLibrary to manage your apps photos, then they will always show under saved photos. According to the Apple Docs the purpose of ALAssetsLibrary is
You use it to retrieve the list of all asset groups and to save images and videos into the Saved Photos album.
If you only need your images accessible inside your app you can handle the reading writing, and presenting of them yourself. This would prevent them from showing up in the camera role or saved photos.
//WRITING TO APP DIRECTORY
NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:#"Photos/"];
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]){
NSError* error;
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error];
}
NSData *imgData = UIImagePNGRepresentation(imageToCrop.image);
NSString *imgName = #"example.png";
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:imgName];
[imgData writeToFile:pngPath atomically:YES];
//READING FROM APP DIRECTORY
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"/Photos/"] error:NULL];
for (int i = 0; i < (int)[directoryContent count]; i++)
{
NSURL *url = [NSURL URLWithString:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"/Documents/Photos/%#",[directoryContent objectAtIndex:i]]]];
UIImage *image = [UIImage imageWithContentsOfFile:[url absoluteString]];
//ADD IMAGE TO TABLE VIEW OR HANDLE HOW YOU WOULD LIKE
}
I have the following code I use to cache photos I load off Flickr in the device's memory:
NSURL *urlForPhoto = [FlickrFetcher urlForPhoto:self.photo format:FlickrPhotoFormatLarge];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [rootPath stringByAppendingString:[self.photo objectForKey:FLICKR_PHOTO_ID]];
NSData *dataForPhoto;
NSError *error = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
dataForPhoto = [NSData dataWithContentsOfFile:imagePath];
} else {
dataForPhoto = [NSData dataWithContentsOfURL:urlForPhoto];
[dataForPhoto writeToFile:imagePath atomically:YES];
}
I want to limit this to 10MB and then if the limit is reached to remove the oldest photo in the cache, how can I get the total size of all the files I've saved and check which one is the oldest?
You can get the size of a file like so
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
int fileSize = [fileAttributes fileSize];
So you can maybe iterate through all the files in the folder and add up the file sizes...not sure if theres a direct way to get the directory size, also theres this SO post talking about this aswell, you can find a solution here
To find the creation date of the file you can do
NSString *path = #"";
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
NSDate *result = [fileAttribs valueForKey:NSFileCreationDate]; //or NSFileModificationDate
Hope it helps
I'm developing this application on an iPad.
These codes for a 'Browse' button allows the user to view the photos from the iPad's gallery.
- (IBAction) BrowsePhoto:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:CGRectMake(200,200,-100,-100) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
When a photo is selected, it will be stored into the application using NSDocumentDirectory.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:#"SavedImage.png"];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Now i have to include a 'Display' button on the first screen.
When tapped on the button, it will show a new view (modal view controller) and displays all the photos in thumbnails/tableview from the NSDocumentDirectory.
When a photo is selected, it will be deleted from the NSDocumentDirectory.
How can i do this?
First of all, while storing the image in Documents folder, try storing them with a naming convention like keep a counter variable and give your images names according to it. Some thing like this:
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", counter]];
Now, once you've all images stored in documents folder and wish to get all of them you can get them by writing this code:
-(NSMutableArray *)GetImage:(NSMutableArray *)arrayImgNames
{
NSMutableArray *tempArray;
for(int i=0;i<[arrayImgNames count]; i++)
{
NSArray *paths1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths1 objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: [arrayImgNames objectAtIndex:i]];
[tempArray addObject:[[UIImage alloc] initWithContentsOfFile:filePath]];
return tempArray;
}
}
Once you've got all images you can display them as thumbnails and then when you wish to delete an image use this method:
-(int)removeImage:(NSString*)FileName1
{
NSFileManager *filemanager=[NSFileManager defaultManager];
NSArray *path1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentdirectory = [path1 objectAtIndex:0];
NSString *filepath=[documentdirectory stringByAppendingPathComponent:FileName1];
if([filemanager fileExistsAtPath:filepath]==TRUE)
{
[filemanager removeItemAtPath:filepath error:nil];
}
return 0;
}
I hope this helps you.
To Populate the table with image you'll need a custom cell. You can refer a tutorial by Apple called AdvancedTableViewCells. It will show you how can you populate your table with images. They have a main thumbnail in every row. You have to customize it and make it 3 or 4 thumbnails as per your requirement. Other than that remove everything from that custom cell.
Currently i'm using these codes to save my images into NSDocumentDirectory. I use this counter as the naming convention for them.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", counter]];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
I use this method because it's easier for me to retrieve all of them by using a loop. I want to retrieve all the images from the NSDocumentDirectory so that i can display them in another view. The following codes show how i retrieve them.
-(NSMutableArray *)GetImage:(NSMutableArray *)arrayImgNames
{
NSMutableArray *tempArray;
for(int i=0;i<[arrayImgNames count]; i++)
{
NSArray *paths1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths1 objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: [arrayImgNames objectAtIndex:i]];
[tempArray addObject:[[UIImage alloc] initWithContentsOfFile:filePath]];
return tempArray;
}
}
However, i do not wish to use the counter as a naming convention for my images. I want to use proper names for them but if i do so, i will have to change my method of retrieving all the images.
Is there any other way that i can retrieve all images other than this method i mentioned?
You can retrieve files using next approach:
NSURL *url = [[AppDelegate sharedAppDelegate] applicationDocumentsDirectory];
NSError *error = nil;
NSArray *properties = [NSArray arrayWithObjects: NSURLLocalizedNameKey, NSURLLocalizedTypeDescriptionKey, nil];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url
includingPropertiesForKeys:properties options:(NSDirectoryEnumerationSkipsPackageDescendants)
error:&error];
In files paths to all files of documents directory will be stored. Next code will help you to get there names:
NSURL *url = [files objectAtIndex:index];
NSString *localizedName = [url lastPathComponent];