I am trying to load an saved image but when I check the UIImage it comes back as nil. Here is the code:
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"/var/mobile/Applications/B74FDA2B-5B8C-40AC-863C-4030AA85534B/Documents/70.jpg" ofType:nil]];
I then check img to see if it is nil and it is. Listing the directory shows the file, what am I doing wrong?
You need to point to the Documents directory within your app then like this:
- (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
Usage:
UIImage *img = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/70.jpg",[self applicationDocumentsDirectory]]];
First, you are using pathForResource wrong, the correct way would be:
[[NSBundle mainBundle] pathForResource:#"70" ofType:#"jpg"]
The whole idea of bundling is to abstract the resource path such as that it will always be valid, no matter where in the system your app resides. But if all you want to do is load that image I would recommend you use imageNamed: since it automatically handles retina resolution (high resolution) display detection on the iPhone for you and loads the appropriate resource "automagically":
UIImage *img = [UIImage imageNamed:#"70.jpg"];
To easily support regular and retina resolution you would need to have two resources in your app bundle, 70.jpg and 70#2x.jpg with the #2x resource having both doubled with and height.
Try loading a UIImage with:
[UIImage imageNamed:#"something.png"]
It looks for an image with the specified name in the application’s main bundle. Also nice: It automatically chooses the Retina (xyz#2x.png) or non-Retina (xyz.png) version.
Your path simply wont work because your app is in a sandbox, and you are trying to use the full path.
You should be using the following instead:
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"70" ofType:#"jpg"]];
or you can use, but is slower than the above:
UIImage *img = [UIImage imageNamed:#"70.jpg"];
Related
I am trying to show various images from a plist file into UIImageView , I wrote my code like this :
NSDictionary *picturesDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Photos" ofType:#"plist"]];
imageArray = [picturesDictionary objectForKey:#"PhotosArray"];
PhotosInAlbum.image = [UIImage imageWithContentsOfFile:[imageArray objectAtIndex:1]];
But actually nothing happens, and my ImageView is empty ! also I have two buttons to forward backward images .
Contents of Plist :
The plist is incorrect, it should be
Root ---- Dictionary
PhotosArray ----- Array
Item 0 ------ String -- Beach.jpg
Then add this code to your viewController.. Be sure that the Interface imageView is link to IBOutlet.
NSDictionary *picturesDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Photos" ofType:#"plist"]];
NSArray *imageArray = [picturesDictionary objectForKey:#"PhotosArray"];
PhotosInAlbum.image = [UIImage imageNamed:[imageArray objectAtIndex:0]];
PhotosInAlbum.image = [UIImage imageWithContentsOfFile:[imageArray objectAtIndex:1]];
this part should be like this
PhotosInAlbum.image = [UIImage imageNamed:[imageArray objectAtIndex:1]];
Try using this:
PhotosInAlbum.image = [UIImage imageNamed:[imageArray objectAtIndex:1]];
Your [imageArray objectAtIndex:1] will only return image name not its path, so in order to use imageWithContentsOfFile you have to specify the path of your image not only image name.
imageWithContentsOfFile: use a path that is the full or partial path to the file.
You can use imageNamed: method instead (which use the name of the file). Just replace
[UIImage imageWithContentsOfFile:[imageArray objectAtIndex:1]];
to
[UIImage imageNamed:[imageArray objectAtIndex:1]];
initially, [UIImage imageNamed:[imageArray objectAtIndex:1]]; would have solved ur problem.
But you are not able to resolve this issue this way which looks like
the problem seems to be with this line
[controller.view addSubview:PhotosInAlbum];
it might be the case your controller.view is nil at the moment you are trying to add ur imageview.
just make sure it isn't. cos if it is then your PhotosInAlbum is not at all getting added as subview to the controller.view.
I am new to this and have searched a lot this week. I am trying to set a background image from a file I have downloaded from a url. I need to save the image for later. Specially if I am not connected to the internet I can still show this image.
I have validated by printing out the contents of the directory that the file exists. This is one of many code that I have tried to make the image appear in the background.
nNSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentPath = [docDir stringByAppendingFormat:#"/mainback.png"];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",documentPath);
if ([[NSFileManager defaultManager]fileExistsAtPath:documentPath]) {
NSData *data = [NSData dataWithContentsOfFile:documentPath];
UIImage *image = [[UIImage alloc] initWithData:data];
NSLog(#"WHAT - %f,%f",image.size.width,image.size.height);
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:documentPath]];
self.view.backgroundColor = background;
[background release];
}
The code finds the image in the directory but I cannot set the image to the background. Please help.
Thanks
Use a UIImageView (Apple documentation linked) instead of doing what you are trying to do with UIColor.
It'll be a lot more straightforward and less problematic.
- (UIImage*)thumbnailImage:(NSString*)fileName
{
UIImage *thumbnail = [thumbnailCache objectForKey:fileName];
if (nil == thumbnail)
{
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/thumbnails/%#.jpg", [[NSBundle mainBundle] resourcePath], fileName];
thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
[thumbnailCache setObject:thumbnail forKey:fileName];
}
return thumbnail;
}
I got this code from http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/ . Can someone tell me how to use this code. I need just a little help how to use this in place of imageNamed.
NSMutableDictionary *thumbnailCache=[[NSMutableDictionary alloc]init];
then add "thumbnails" folder to ur resource folder then put ur png there
- (UIImage*)thumbnailImage:(NSString*)fileName
{
UIImage *thumbnail = [thumbnailCache objectForKey:fileName];
if (nil == thumbnail)
{
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/thumbnails/%#.jpg", [[NSBundle mainBundle] resourcePath], fileName];
thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
[thumbnailCache setObject:thumbnail forKey:fileName];
}
return thumbnail;
}
example
add foo.png to resource folder
//here create UIImageView object then
UIImageviewObject.image=[self thumbnailImage:#"foo.png"];
The code uses a NSMutableDictionary *thumbnailCache to cache UIImage instances. The code assumes that in the app bundle, there's a directory thumbnails with scaled down versions of their images.
The method now first looks in the thumbnailCache dictionary whether the thumbnail for the given image (which is only a filename without full path, e. g. myimage.png). If the dictionary did not contain an image already, the image is loaded from the thumbnails directory (using imageWithContentsOfFile: instead of imageNamed:, since the authors claim the later causes trouble). The loaded image is then stored in the dictionary so the next time the app asks for the thumbnail, it can use the already loaded instance.
For this code to work correctly in your app, you need to add a thumbnails folder to your project. When you add it to your project, be sure to select "Create folder references for any added folders" instead of the default "Create groups for any added folders". Only then you will get a subdirectory in your app's main bundle, otherwise all files are put into the same top-level folder.
But the whole point is that the author claims:
Avoid [UIImage imageNamed:].
Instead, have a NSMutableDictionary.
Look up images in the dictionary.
If found, use that.
If not found, load image using [UIImage imageWithContentsOfFile:] to manually load the image and store it in the dictionary.
thumbnailCache is NSMutableDictionary declared in header file and it should be initialized in .m init method or equivalent method.
If u have the images in the resources (with jpg format, else change the .jpg to .png in the code), then the line should be like
NSString *thumbnailFile = [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], fileName];
Instead of using
UIImage *thumbImage = [UIImage imageNamed:#"thumb.png"];
UIImage *thumbImage = [self thumbnailImage:#"thumb.png"];
I am trying to set image to UIImageView programmatically but it does't work. I have following code.
[image setImage:[UIImage imageNamed:[self localImagePath:NO]]];
and
-(NSString *)localImagePath:(BOOL)forSave {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);
NSString *picturesDirectory = [paths objectAtIndex:0];
NSString *picturesPath = [picturesDirectory stringByAppendingPathComponent:#"image.png"];
if (forSave || [[NSFileManager defaultManager] fileExistsAtPath:picturesPath]) {
return picturesPath;
}
else {
return [[NSBundle mainBundle] pathForResource:#"image" ofType:#"png"];
}
}
Is it possible to set image to UIImageView on run time from different mediums?
The imageNamed: method takes only the filename as an argument, not a path. Also it will look for that file in the main bundle only. Try using imageWithContentsOfFile: instead.
You'll have to use two different ways to load the image
[UIImage imageNamed: name] for the resource based one
[UIImage imageWithContentsOfFile: filename] for the one you found locally.
consider changing your method to return the UIImage and use the appropriate loading method internally.
Use [UIImage imageWithContentsOfFile:[self localImagePath:NO]], instead of [UIImage imageNamed:...] for the one you found using your localImagePath method.
Here is what I'm doing, when I create an image with the path in the bundle:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"image" ofType:#"jpg"]];
What I want to do is trying to find the path for my image but without using the extension, without using 'ofType' (because the name of my image and her extension is store in my database) something like that:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"image.jpg"]];
But I don't know how to do it.
Best regards,
Why don't you split the string that you get from the DB?
NSString* fullFileName = #"image.jpg";
NSString* fileName = [[fullFileName lastPathComponent] stringByDeletingPathExtension];
NSString* extension = [fullFileName pathExtension];
Now you can simply use:
[[NSBundle mainBundle] pathForResource:fileName ofType:extension]];
You can easily use the NSBundle method without passing the extension, just pass nil for extension.
[[NSBundle mainBundle] pathForResource:#"image.jpg" ofType:nil];
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
return myData;
}
taken from http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW21
Could be easily adapted if you wanted it to return a UIImage instead of an NSData.
Also, you don't say if you are saving the images to the documents directory, or adding them to your app bundle before compiling. because if it's the latter, you can use [UIImage imageNamed:(NSString *)filename] to get the image. It expects an extension as part of the file-name.
The easiest way is to store the name and file type in your database separately, and retrieve them using the first method.I'm not sure that you can be successful in implementing the latter one.
I found that with an extension of ".jpg" it was necessary to use ofType for the extension for the app to work on an iPod Touch, whereas with an extension of ".png" I could just put "image.png" in pathForResource and say ofType:nil. But all versions worked on the simulator.
The app bundle contains the image file, and I am using:
[[NSBundle mainBundle] pathForResource:#"Auto" ofType:#"jpg"]
to get a path.