store file in NSDocumentDirectory of iPhone - iphone

I am using a UIImagePickerController in my application.
After selecting an image by user,
image should be saved at application Documents Directory,
my Code is Give Below.
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissModalViewControllerAnimated:YES];
NSData *imgData = UIImagePNGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"]);
UIImage *img = [[UIImage alloc] initWithData:imgData];
stuImgView.image = img;
[img release];
//write image
NSString *imageFilename = [NSString stringWithFormat:#"%i.jpg", currentStudent.stuNo];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
UIImage *stuImg;
BOOL success;
NSFileManager *fm=[NSFileManager defaultManager];
// how to store file at documents dir????
}
i dont know how to use file manager to store a file?
Help me Out.
Thanks in advance.

You can use writeToFile:atomically::
[imgData writeToFile:path atomically:NO];

Related

Check if file exists in resourses/project navigator

I need to check if an image exists in the project navigator. If it doesn't it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:#"23451.jpg"];
So I need to check if the image exists, if not download it. I tried to do this as followed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Set image
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"12345.jpg"];
//Check if the image exists at a given path
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
//If the image doesn't exists download it.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
If everything goes the right way the image is saved at the above path. But I still am not able to use this image with
[UIImage imageNamed:#"12345.jpg"];
I have got the feeling that i'm saving the images in a different directory than I should be saving them to.
Do you have any idea on how I should do this?
imageNamed will only work form image in the app bundle, not those stored in the Document directory. And you can't add the image to the app bundle, it readonly.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
There is no need to do this, you are now JPG a JPG:
if (!imageExists)
{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.mywebsite.com/12345.jpg"]];
[data writeToFile:imagePath atomically:YES];
}
NSData* data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:imagePath], 0.8)];
[data writeToFile:imagePath atomically:YES];
I did something similar .. here are some excerpts of the code .. not the complete code ...
- (void)loadAndStoreImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *theurlPortrait = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"portraitImageUrl"] ];
NSLog(#"Image url %# ",theurlPortrait);
imageDataPortrait = [NSData dataWithContentsOfURL:theurlPortrait];
[theurlPortrait release];
imagePortrait= [[UIImage alloc]initWithData:imageDataPortrait];
oldPathPortrait = [documentsDirectory stringByAppendingPathComponent:#"pt_wallpaper_1.png"];
NSURL *theurlLandscape = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"landscapeImageUrl"]];
imageDataLandscape = [NSData dataWithContentsOfURL:theurlLandscape];
[theurlLandscape release];
imageLandscape= [[UIImage alloc]initWithData:imageDataLandscape];
oldPathLandscape = [documentsDirectory stringByAppendingPathComponent:#"ls_wallpaper_1.png"];
[self replaceImages];
}
-(void)replaceImages{
//check if images were fully downloaded or corrupted.
if (isUserSignedIn) {
if (imageDataPortrait && imageDataLandscape) {
[UIImagePNGRepresentation(imagePortrait) writeToFile:oldPathPortrait atomically:YES];
[UIImagePNGRepresentation(imageLandscape) writeToFile:oldPathLandscape atomically:YES];
NSLog(#"IMAGES REPLACED");
NSDate *currentDate=[NSDate date];
[[ NSUserDefaults standardUserDefaults] setObject:currentDate forKey:#"previousDate"];
}
}
}

How do I save an image to the sandbox - iPhone SDK

I have pulled an image out of the UIImagePicker thingy, and I would like to temporarily save it to the sandbox environment, in either the documents folder, or some other similar equivalent. However, I do not know how to do this, please could someone help me? Thanks
At the moment the image is a UIImage
Saving an image:
-(void)saveImage:(UIImage*)image{
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/someImageName.png"];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
}
Loading an image
-(UIImage)loadImage{
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/someImageName.png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
}
-(void)SaveImage
{
NSData *data;
NSArray *paths;
NSString *documentsDirectory,*imagePath ;
UIImage *image=[UIImage imageNamed:#"public.png"];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"public.png"]];
data = UIImagePNGRepresentation(image);
[data writeToFile:imagePath atomically:YES];
}

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];

How to store image in big size in local?

I am storing an image locally but my image is store in small size. i want to store this image in orignal size how can i do this ?
my code for store image is like this ..
NSString *myurl = [[NSString alloc]init];
myurl =[data valueForKey:#"large_image"];
NSData *mydata = [[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]] retain];
UIImage *myimage = [[[UIImage alloc] initWithData:mydata] retain];
NSData *imageData = UIImagePNGRepresentation(myimage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *imageName = [NSString stringWithFormat:#"image.png",documentsDirectory];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:Imagename];
[imageData writeToFile:fullPathToFile atomically:YES];
this is stored image
and this is orignal image
i am doing wrong in code. this is the reason. why this happend.
may be it is because of leak ok knowledge that time. :)
other wise all things is correct only.

Compressing / down size / resize image while storing image in iPhone application

To understand my question please go through following:
In my application user first taps on a button.
Image picker controller is displayed
user selects images / an image from it.
all that images must be saved to my iPhone application.
I have already implemented this and for doing this I have implemented following code.
-(IBAction)setPhoto:(id)sender {
facPhotoPicker=[[UIImagePickerController alloc]init];
facPhotoPicker.delegate=self;
facPhotoPicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
facPhotoPicker.allowsImageEditing=YES;
facPhotoPicker.navigationBar.barStyle=UIBarStyleBlackOpaque;
[self presentModalViewController:facPhotoPicker animated:YES];
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {
NSData *imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
UIImage *img=[[UIImage alloc] initWithData:imgData];
facImgView.image=img;
[img release];
NSString *str=[NSString stringWithFormat:#"%i.jpg",[currentFaculty facultyNo]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], str];
[imgData writeToFile:path atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
But the problem is the user's iPhone may have larger images.
I don't want to store that large images within application.
for example
user selects an image having size of 1200 x 800
But I want only 80 x 80 size image
selected images should be down sized to my requirement / 8 mb image to less then 500 kb
how to store image within resource directory instead of storing in documents directory?
This is solved.
The main key for downsizing. I downsized an image up to 116 kb.
NSData *imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],compressionRatio);
while ([imgData length]>50000) {
compressionRatio=compressionRatio*0.5;
imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],compressionRatio);
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
double compressionRatio=1;
NSData *imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],compressionRatio);
while ([imgData length]>50000) {
compressionRatio=compressionRatio*0.5;
imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],compressionRatio);
}
UIImage *img=[[UIImage alloc] initWithData:imgData];
facImgView.image=img;
NSLog(#"%#",[info objectForKey:#"UIImagePickerControllerOriginalImage"],3);
[img release];
NSString *str=[NSString stringWithFormat:#"%i.jpg",[currentFaculty facultyNo]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#", [paths objectAtIndex:0]];
path=[path stringByDeletingLastPathComponent];
path=[NSString stringWithFormat:#"%#/%#",path,str];
[imgData writeToFile:path atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}
2) You can not store in the Resources directory now in any directory within the application.
any one can store in resource directory / up level directory of documents directory by implementing following logic.
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
NSData *imgData=UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
UIImage *img=[[UIImage alloc] initWithData:imgData];
facImgView.image=img;
NSLog(#"%#",[info objectForKey:#"UIImagePickerControllerOriginalImage"],3);
[img release];
NSString *str=[NSString stringWithFormat:#"%i.jpg",[currentFaculty facultyNo]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#", [paths objectAtIndex:0]];
path=[path stringByDeletingLastPathComponent];
path=[NSString stringWithFormat:#"%#/%#",path,str]; // storing path
[imgData writeToFile:path atomically:YES]; // stores successfully
[picker dismissModalViewControllerAnimated:YES];
}