How to call the local image file and display into the imageviewcontroller - iphone

I create the one application in that create the locally store the file in payment while the application not be deleted.
This I have done: I download the file and store into locally (applications document folder).
Now I am having trouble with this:
While the after the image is downloaded then I fetch into locally and that image will not display. In NSLog following url is generated and i can't display the image.
/Users/username/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/F233ED88-1546-4FB0-BE93-0E0FB8C8C3D6/Documents/NationalMedalofArts-150x150.jpg
Edit:
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#",
#"/Users/username/Library/Application Support/iPhone Simulator/5.0/Applications/F233ED88-1546-4FB0-BE93-0E0FB8C8C3D6/Documents/NationalMedalofArts-150x150.jpg"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSLog(#"%#",imageData);
UIImage *image = [UIImage imageWithData:imageData];
self.imgView.image = image;
when the NSLog the NSData then it's NULL to display

This is better:
NSString *fileName = #"NationalMedalofArts-150x150.jpg";
NSString *path = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(), fileName];
self.imgView.image = [UIImage imageWithContentsOfFile:path];

Try using this:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:#"NationalMedalofArts-150x150.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:file];
UIImage *image = [UIImage imageWithData:imageData];
self.imgView.image = image;
When accessing files in the documents-folder of the application, which is where images and those sorts of things are found, you must use the first line to find the path to the documents-folder. The code above should work for you.

Related

image retrieving in sqlite

I am using using sqlite in my project
Previously I had saved image in data but now I am saving image in bytes like following code
NSUInteger len = [entObject.photoImageData length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [entObject.photoImageData bytes], len);
insertString = [NSString stringWithFormat:#"INSERT INTO TBL_COUNTDOWN (DAIRYID,EVENTID,DESCRIPTION,EVENTIMAGE) VALUES (\"%#\",\"%d\",\"No Data\",\"%s\")",self.dairyId,self.eventId,byteData];
For retrieving image I am using following code
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 3) length: sqlite3_column_bytes(statement, 3)];
NSLog(#"dataForCachedImage/getAllEvents is %#",dataForCachedImage);
UIImage *cachedImage = [UIImage imageWithData:dataForCachedImage];
NSLog(#"cachedImage/getAllEvents is %#",cachedImage);
For dataForCachedImage in NSLog I am getting data but for cachedImage I getting null
I dont no whats wrong in my code. Please help me
Thanks in advance
You can save image to document directory and store its path to sqlite database
save Image code is as follows
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
NSString *filePath= [NSString stringWithFormat:#"%#/%#.jpg", DOCUMENTS_FOLDER,caldate];
NSURL *url = [NSURL fileURLWithPath:filePath];
UIImage *image = [UIImage imageNamed:#"name.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
anytime you want to retrieve Image then get it then use following method to getImage
- (UIImage*)getImage
{
NSString *imagePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:#"imagename.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
return img;
}
deleting file
NSFileManager *fileManager=[NSFileManager defaultManager];
[fileManager removeItemAtPath:savedFilePath error:nil];
may this will help you..

trying to save jpeg to Documents directory of app

So I have a function which gets an image from a URL which looks like this:
- (UIImage *) getImageFromURL:(NSString *)fileURL {
UIImage * result;
NSData * img_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:img_data];
return result;
}
and then a function which saves the image from a UIImage Which looks like this:
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:#"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
NSLog(#"Image named %# wrote to %#", imageName, directoryPath);
} else {
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
The issue I am facing is that when I run a UIImage through the saveImage function I dont think it is saving the image. This is because when I check for a UIImage imageNamed:#"Documents/filenamesavedas.jpeg" it returns (null). The image does however download correctly.
Here is my Documents Directory path function:
- (NSString *)getDocumentsDirectoryPath {
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(documentsDirectoryPath);
return documentsDirectoryPath;
}
Here is where I am downloading and trying to save the image:
dispatch_async(jsonQueue, ^{
// check to see if data authenticate runs successfully.
NSString *documentsDirectoryPath = [util getDocumentsDirectoryPath];
UIImage *imageToSave = [util getImageFromURL:[properties objectForKey:#"current_group_logoURL"]];
[util saveImage:imageToSave withFileName:[properties objectForKey:#"home_venue_logo"] ofType:#"jpeg" inDirectory:documentsDirectoryPath];
NSLog(#"Group Logo URL %#", [properties objectForKey:#"current_group_logoURL"]);
NSLog(#"Current Group Image %#", [properties objectForKey:#"home_venue_logo"]);
UIImage *testToSeeItHasDownloaded = imageToSave;
NSString *imageLocation = [documentsDirectoryPath stringByAppendingPathComponent:[properties objectForKey:#"home_venue_logo"]];
NSData *data = [NSData dataWithContentsOfFile:imageLocation];
UIImage *testToSeeImageHasSaved = [UIImage imageWithData:data];
NSLog(#"testToSeeImagehasDownloaded: %#", testToSeeItHasDownloaded);
NSLog(#"image location to save to: %#", imageLocation);
NSLog(#"testToSeeImagehasSaved: %#", testToSeeImageHasSaved );
});
The Console returns this:
2012-10-22 16:27:45.642 asdaf[46819:1d807] Group Logo URL http://somesite.com/50a0e42619424ba551a956511c098656.jpeg
2012-10-22 16:27:45.642 asdaf[46819:1d807] Current Group Image 50a0e42619424ba551a956511c098656.jpeg
2012-10-22 16:27:45.649 asdaf[46819:1d807] testToSeeImagehasDownloaded: <UIImage: 0xb09ed50>
2012-10-22 16:27:45.649 asdaf[46819:1d807] testToSeeImagehasSaved: (null)
testToSeeImagehasSaved should return null. But what am I doing wrong? Thanks.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//documentsDirectory is your documents directory path
//Now append your image name in this path
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"ImageName.jpeg"];
//convert your image in NSData
NSData *imageData = UIImagePNGRepresentation(image);
//Now write it at path
[imageData writeToFile:imagePath atomically:NO];
You can get this image in same way
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
Edit:
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [imageName stringByAppendingString:extension];
//Note extension should be like .png, .jpg, .jpeg dont forget dot (.).
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:imagePath atomically:NO];
}
Well i dont now about your whole code but why you're passing an UIImage object when you have to save your image in documents directory. You can pass NSData as well in your method. You're doing more.
Your problem is you're saving .jpg image each time and at the time of retrieving you're trying to find .jpeg image on same path thats why you're getting null value. See this line in your saving method -
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
this line doesn't look right to me:
UIImage *testToSeeImageHasSaved = [UIImage imageNamed: [#"Documents/" stringByAppendingString: [properties objectForKey:#"home_venue_logo"]]];
I think you have to do:
UIImage* image = [UIImage imageWithContentsOfFile:"YOUR_FILE_PATH"];
[UIImage imageNamed:"image_name"] is good only for images attached to your project
When you save it in the document folder, it does not exacly saves it in the "Document" directory but rather something like
path=/var/mobile/Applications/144B3628-5258-4939-8B80-006EC5BE45B2/Library/Caches/6_1.png
So to retreive your image you should use
NSString *uniquePath = [directory stringByAppendingPathComponent: filename];
image = [UIImage imageWithContentsOfFile: uniquePath];
where directory is the path you used to save it and filename the name of your jpeg.
[UIImage imageNamed:#"Documents/filenamesavedas.jpeg"]
Doesnt take paths it searches your bundle for the file with a specific name.
Locate the file using calls to NSFileManager and use the expected path and file name.

Passing uiimage to new view

I am trying to create an array of images (from the web) and then pass this array to a new view. Here is the code I'm using:
WebViewController *webController = segue.destinationViewController;
NSURL *url = [NSURL URLWithString:[gift objectForKey:#"smallImageUrl"]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
webController.image = image;
Also in my WebViewController.h i have:
#property(strong,nonatomic) UIImage *image;
But when I try to use "image" in WebViewController.m all i get is a (null) value. Where am I going wrong? Thanks!
UPDATE:
The problem appears to not be as I stated before. The image makes it to WebViewController. I am trying to save the image to an array which must be where my problem lies. This is the code I have for that in a saving method (in WebViewController.m):
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
[imageArray addObject:image];
[imageArray writeToFile:imageFileName atomically:YES];
also in my viewdidload i do:
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
imageFileName = [NSString stringWithFormat:#"%#/imageArray",documentsDirectory];

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

Save image to device

Hi i cant seem to get his code to work
//Save Image To Device
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.ImageURLS objectAtIndex:0]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"saving jpg");
NSString *jpgFilePath = [NSString stringWithFormat:#"%#/%#.jpg",docDir,[self.NameArray objectAtIndex:0]];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpgFilePath atomically:YES];
and i am getting the image via
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *jpgFilePath = [NSString stringWithFormat:#"%#/%#.jpg",docDir,[self.NameArray objectAtIndex:[indexPath row]]];
UIImage *image = [UIImage imageNamed:jpgFilePath];
Any help ?
Thanks
Change the last line of your code to
UIImage *image = [UIImage imageWithContentsOfFile:jpgFilePath];
UIImage's +imageNamed: searches the app bundle for a file with a given name, which is not what you need.