Downloading and saving images in iOS - iphone

I am creating an iPhone app and in that I want to download multiple image files from web service. And I want to save the images in the local folder in the app itself and save the path to each files in SQLite database. How can I implement this? Please help.

**// Get an image from the URL below**
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"yorimageurl"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
**// Let's save the file into Document folder.**
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#/test.png",Dir];// this path if you want save reference path in sqlite
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegPath = [NSString stringWithFormat:#"%#/test.jpeg",Dir];// this path if you want save reference path in sqlite
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
>> Update Additional:
You need to save image name(unique name that you can do early..right..!!) in sqlite database and you can make path or retrieve image using that name as i shown below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"test.png"];// here you jus need to pass image name that you entered when you stored it.
Hope, this will help you...

After implementing #Nit's code.. you can refer This for insert record in database.
This is showing how to insert record in DB. and for getting path read my comments in #Nit's answer.
UPDATE:
For getting path of each downloaded file you have to keep unique name for each file. Now you will have the path where you are writing file that is unique path for every file. Now you simply need to execute insert query every time you download a file or need to save filepath in array and execute query later according to your requirement. Don't forget to give different file name to every file otherwise only single file will be there and your path will be same.
For getting unique filename you can use timestamp:
NSString *fileName = [NSString stringWithFormat:#"%lf.png", [[NSDate date] timeIntervalSince1970];
UPDATE2:
You have path now like: /Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/84A837AA-7881-4D99-B6E2-623DC9A2E5D3/Documents/test.png
For getting Image in Image view:
UIImage *img = [UIImage imageWithContentsOfFile:yourPath];
//[UIImage imageWithData:[NSData dataWithContentsOfFile:yourPath]];
UIImageView *imgView = // Alloc + Init + Setting frame etc
imgView.image = img;
This will show image in your imageview
Hope this helps

Related

Imageview image save in SQL database using URL in iOS

I want to save displayed UIImageview image in SQL database. I am capturing the image using the camera/albums/library which are displayed in UIImageview. I want to save this image in my SQL database using URL.
Also I need to display this image in another view.
How can I take a path(URL) of my imageview image? How can I store this path(URL) & also store & display into another view?
How to grab the UIImage and write to internal directory:
UIImageView *imageView = "[your image]";
// define your own path and storage for image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
documentPath = [documentPath stringByAppendingPathComponent:#"test.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
[imageData writeToFile:documentPath atomically:YES];
How to get the NSURL/NSString for a file path in internal directory:
// specify fileURL as it is an internal file, don't use URLWithString:
NSURL *fileURL = [NSURL fileURLWithPath:documentDirectory];
// store as a string in database
NSString *fileURLString = fileURL.path;
Please take note that the NSURL for local file is different with normal NSURL.
// for normal URL
NSURL *webURL = [NSURL URLWithString:"http://www.google.com/"];
[webURL absoluteString]; // -> http://www.google.com/
// for local file path URL
NSURL *localURL = [NSURL fileURLWithPath:"/User/path/samplefile.ext"];
[localURL absoluteString]; // -> file://User/path/samplefile.ext
[localURL path]; // -> /User/path/samplefile.ext
just save name of your image in database and store image in phone memory...it will be easy or this way try this line
UIImage *img = [UIImage imageWithContentsOfFile:(the file path)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];

Saving in NSDocumentDirectory

Having weird problem with my NSDocumenDirectory saving.
Here is a sneak preview:
First I pick images ( in my imagePickerViewController):
in my PreviewController:
So at first try, it was okay.
Then I revisit the imagePickerViewController to add another image:
in my PreviewController:
This is where the problem occurs. At the image above, it recopies the last image from the old preview (like a duplicate). I dunno what Im doing wrong in my codes. But Im saving it when a file exist. Kindly see:
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:#"firstSlotImages%d.png", i]];
if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
NSLog(#"file doesnt exist");
} else {
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 need is to just reAdd AGAIN the same image with the new one.
Same as, like the last preview.
The four images are passed in the sequence that they show in the preview, so in the first example the orange cat is third, and in the second example, the orange cat is fourth. The new image isn't saving because it is third, and you already have a file named "firstSlotImages2.png". If you re-save each image without checking if the file exists, you should get the result you are looking for.
There's a key in the media info: UIImagePickerControllerMediaURL which returns an NSURL, convert it to a string and get the the lastPathComponent. Use this as the file name to save to the directory you are saving it to. You can then save the reference to these images by saving this same file name either in an NSMutableArray, or an NSMutableDictionary

Why might this code be giving me null?

Scroll down to EDIT 1. This top bit is irrelevant now.
This is my code:
NSMutableDictionary *dictionary = [self.media objectAtIndex:index];
NSLog(#"dictionary: %#", dictionary);
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
UIImage *originalImage = [UIImage imageWithContentsOfFile:originalImagePath];
NSLog(#"original image: %#", originalImage);
return originalImage;
And my NSLog:
dictionary: {
IsInPhotoLibrary = 1;
MediaType = 0;
OriginalImage = "/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg";
}
path: /var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg
original image: (null)
Any ideas why this might be coming out as null, despite everything appearing to be in place?
EDIT:
This is the code to write the image to file:
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Images/"];
NSString *name = [NSString stringWithFormat:#"%#.jpg", [JEntry generateUuidString]];
NSString *filePath = [path stringByAppendingPathComponent:name];
[fullImageData writeToFile:filePath atomically:YES];
NSLog(#"original image 2: %#", [UIImage imageWithContentsOfFile:filePath]);
}
This NSLog also comes out as null. So the problem lies here, most likely. Any ideas?
EDIT 2:
So, back-tracing even more now, and I've realised that it's because this fails:
[fullImageData writeToFile:filePath atomically:YES];
You can return a bool on that line, telling if it was successful or not, and it's returning NO for me. Any ideas why this might be?
EDIT 3:
The image that gets passed in is NULL. Trying to figure out where that's gone wrong now.
Almost certainly your file does not exist. Modify your code as follows to log if a file exists or not:
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:originalImagePath];
NSLog(#"file exists: %d", fileExists);
Possible Reasons:
The file at originalImagePath does not exist.
UIImage can not initialize an image from the specified file, because the data is corrupted (maybe the data is empty or incomplete)
the file can not be accessed because of iOS file permissions (i.e. when accessing files beyond the app sandbox)
Have you checked that the image file is really placed on path in dictionary? You may use the iExplorer utility for that.
Also pay attention to the file name case, so it's extension is 'jpg' not 'JPG'.
Finally you should check, whether it's a valid image file, by opening it with some image viewer.
are you sure that the jpg file "E9904811-B463-4374-BD95-4AD472DC71A6.jpg" is there in that folder?
try to open the app file installed in the iPhone/ipad simulator clicking on yourFile.app
with ctrl key and choose to open package contents the open your folder images...
to get a fast link to your documents folder:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"doc:%#",docsDir);
your app should be in its parent folder

How to retrieve photo library path?

I am using photos saved in photo library in my application.
how can I retrieve path of photos saved in photo library?
I had converted that UIImage into NSData and saved that data in application's sandbox(in one file).Using sqlite , I have created a database and saving file path in database.
Whenever i need image, I retrieve NSData from file path saved in database.
NSMutableData *data=[[NSMutableData alloc]init];
data =UIImagePNGRepresentation([UIImageimageNamed:#"image.png"]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"first.txt"]; [data writeToFile:filePath atomically:YES];
NSString *m=[[#"'"stringByAppendingFormat:filePath]stringByAppendingFormat:#"'"];
NSString *query=[[#"INSERT INTO newtable (image) VALUES (" stringByAppendingFormat:m]stringByAppendingFormat:#")"];
NSLog(#"query....%#",query);
[obj configureDatabase:#"Editerdb.rdb"];//function to configure database
[obj insertInTable:query];// function to insert into db
This code is working.
Is there any simple way to do that?
Well first of all in the first line you are going to have a memory leak. Check the documentation on UIImagePNGRepresentation to for assistance. so remove the the first line of code. and use NSData instead of NSMutableData coz you are not changing the contents of image.
and second of all you are not saving the image path in database but the image itself again for this referrer to documentation on UIImagePNGRepresentation so when to want to image just retrive the NSData object from database and convert the NSData to UIImage using imageWithData:

store images in iPhone application

I am simply creating a student management system in iPhone.
There I need to store student's small images,
Which should be appear in tableView,
Ok, I know how to work with tableView...
how to work with database...
But question is
Where to store images
how can we obtain the path of stored images..
Do i have to store entire images to database...
Or
i have to store relative path of image to database...
What is suggested by You masters?
Thanks in advance for helping me.
You can create image files on the file system of the device in the Document directory. Use something like this:
// Generate a unique user filename
NSString *imageFilename = [NSString stringWithFormat:#"student_image_%#", uniqueIdentifier];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
NSData *storage = [image UIImagePNGRepresentation]; // or UIImageJPEGRepresentation
[storage writeToFile:path atomically:NO];
Best Regards,