imageNamed is evil - How to use the function - iphone

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

Related

Check if exists a string inside a plist file

Hello guys i try to check a single line STRING inside my plist file, in my detail view I need to implement a IF like a:
NSString *data = [[NSBundle mainBundle] pathForResource:#"name" ofType:#"plist"];
NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:data];
self.myMutableDictionary = dataDict;
if (name.text == [myMutableDictionary objectForKey:#"emittente"]){
UIImage *image = [UIImage imageNamed:#"star_on.png"];
[Star setImage:image];
} else {
UIImage *favImg = [UIImage imageNamed:#"star_Off.png"];
[Star setImage:favImg];
}
But dosent work, i think no reading inside the plist file, any idea or metod for do that?
Thanks.
Actually, your code looks almost fine. Just check the following:
Does your plist contain the key #"emittente" on the top level? If not, you have to descend down your dictionaries or arrays to get to the right level.
Also, you are comparing pointers in your if statement, not strings. Use this instead:
if ([name.text isEqualToString:myMutableDictionary[#"emittente"]) ...
BTW: you should not use uppercase instance variable names.

Pictures put into a array Ios developing

I have a folder with pictures in my project and i like to know how i could put this pictures from the folder into a array
How should i do that?
I tried this to put the images in the array
UIImage*image = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
NSArray*images = [[NSMutableArray alloc]initWithContentsOfFile:image];
You could do the following, getting the array of filenames and then filling another array with the images, themselves (assuming that's what you were trying to do).
NSMutableArray *imagePaths = [[NSMutableArray alloc] init];
NSMutableArray *images = [[NSMutableArray alloc] init];
NSArray *imageTypes = [NSArray arrayWithObjects:#"jpg", #"jpeg", #"gif", nil];
// load the imagePaths array
for (NSString *imageType in imageTypes)
{
NSArray *imagesOfParticularType = [[NSBundle mainBundle]pathsForResourcesOfType:imageType
inDirectory:#"Images"];
if (imagesOfParticularType)
[imagePaths addObjectsFromArray:imagesOfParticularType];
}
// load the images array
for (NSString *imagePath in imagePaths)
[images addObject:[UIImage imageWithContentsOfFile:imagePath]];
As an aside, unless these are tiny thumbnail images and you have very few, it generally would not be advisable to load all the images at once like this. Generally, because images can take up a lot of RAM, you would keep the array of filenames, but defer the loading of the images until you really need them.
If you don't successfully retrieve your images, there are two questions:
Are the files included in my bundle? When you select the "Build Phases" for your Target's settings and expand the "Copy Bundle Resources" (see the image below), do you see your images included? If you don't see your images in this list, they won't be included in the app when you build it. To add your images, click on the "+" and add them to this list.
Are the files in a "group" or in an actual subdirectory? When you add files to a project, you'll see the following dialog:
If you chose "Create folder references for added folders", then the folder will appear in blue in your project (see the blue icon next to my "db_images" folder in the preceding screen snapshot). If you chose "create groups for added folders", though, there will be the typical yellow icon next to your "Images" group. Bottom line, in this scenario, where you're looking for images in the subdirectory "Images", you want to use the "Create folder references for added folders" option with the resulting blue icon next to the images.
Bottom line, you need to ensure the images are in your app bundle and that they are where you think they are. Also note that iOS is case sensitive (though the simulator is not), so make sure you got the capitalization of "Images" right.
If I am understanding your question correctly initWithContentsOfFile doesn't do what you are expecting, per the documentation:
"Initializes a newly allocated array with the contents of the file specified by a given path."
Additionally, pathsForResourceOfType is already creating an array, not a UIImage, you can simply do:
NSArray* images = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
[[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
already returns an array of these objects. Change your line to this:
NSArray *images = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
Note that this array will only hold the paths for all your images. In order to make images of them you need to call
for(NSString* imagePath in images) {
UIImage* anImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
//do something with your image here.
}
Hope that helps
Read the documentation of initWithContentsOfFile method of NSArray:
The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). The objects contained by this array are immutable, even if the array is mutable.
In your case you need to use NSFileManager to enumerate files in directory. Here is the example of directory enumeration from documentation:
NSFileManager *localFileManager=[[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum =
[localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: #"doc"]) {
// Create an image object here and add it to
// mutable array
}
}
[localFileManager release];
Try this:
NSMutableArray* paths=[NSMutableArray new];
NSFileManager* manager=[NSFileManager new];
NSBundle* bundle= [NSBundle mainBundle];
NSDirectoryEnumerator* enumerator= [manager enumeratorAtPath: [bundle bundlePath] ];
for(NSString* path in enumerator)
{
if([path hasSuffix: #".jpg"] || [path hasSuffix: #".jpeg"] || [path hasSuffix: #".gif"])
{
[paths addObject: path];
}
}
For explanations I suggest that you look at NSDirectoryEnumerator documentation.

Save Image With In App

What I am needing to do is, take a picture or choose one form the photo library, then save it within the app so that it isn't visible anywhere else but within the app. For example it would be like "My Secret Folder" where images are only seen within the app. I am not making a secret folder app.... So don't worry... =)
I am sorry I don't have much code to show, but I have no idea how to do this.
I was looking at the Rich Text File and was wondering if that was the way to go and if it can even store images, or if I have to do it a different way.
Thanks,
Denali Creative LLC
P.S.
What I am looking to do is save MORE THAN ONE image within the application. So i will need to be able to name what the Image or what ever the image is saved into's file name.
Lookup/Search code for using UIImagePickerController
Convert Image to Data using Convert Image to Data
Save the data to the document folder. No other apps can access your documents folder.
folder, see this post Save Image to Disk
Read data from disk, convert to image and display to reverse process.
You can save the images within your application's Sandbox
The Documents folder is backup during syncs, and Library/Caches folder is not. That gives you a choice between levels of secrecy.
Once you have your image (UIImagePickerController and a class that follows <UIImagePickerControllerDelegate> protocol), convert it to NSData and archive it to your desired folder.
Something like
NSData * imageData = UIImagePNGRepresentation (image);
NSData * imageData = UIImageJPEGRepresentation (image);
when you unarchive the NSData, you can create the image with
[UIImage imageWithData:data];
So u dont want other app to recognize ur images. I am not sure but this might help you. Instead of standard png or jpg extention, just replace a dummy extention like .abc which other apps cant recognize. There might be other ways but I was using this method.
Extract your image from the PhotoPicker info dictionary in the photo picker delegate callback.
Set up a subdirectory somewhere under your /Documents folder, and write the image there.
NSData *pngData = UIImagePNGRepresentation(_myUIImage);
BOOL successFlag = [pngData writeToFile:documentDirectorySubFolder options:0x0 error:&error];
use UIImagePickerController class and implement it delegate
There is a delegate method of image picker view delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ;
This method is get called when you select the picture from photo Library or take picture from camera.That is good to save your images in core data base then it is only visible with in your app.
I think this idea may be help for you. You can create one app for that like with SQLIte. in which you save your images within your app. but the problem is the images which you save in your app and keep safe from others, you have to manually remove from image gallery
I recommend that you store the images in the Documents Directory and read them from there as it is the most appropriate location to store app content.
Save Image to Documents Directory
-(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];
} else {
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
Load Image From Documents Directory
-(UIImage *)loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
How-To
//Definitions
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//Save Image to Directory
[self saveImage:imageFromURL withFileName:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];
//Load Image From Directory
UIImage * imageFromWeb = [self loadImage:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];

UIImage from file problem

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

How to load images from the Documents folder that have been saved dynamically?

I have problem with loading images from the Documents folder of iPhone application into the tableView.
In a separate request, I check on the server all the images available and download them into the "images" folder under Documents. I am pretty sure that the images are saved correctly.
NSString *filePath = [imagesFolderPath stringByAppendingPathComponent:imageFileName];
[urlData writeToFile:filePath atomically:NO];
NSLog(#"Saved to file: %#", filePath);
2010-01-22 17:07:27.307 Foo[2102:207] Saved to file: /Users/Hoang/Library/Application Support/iPhone Simulator/User/Applications/6133A161-F9DC-4C92-8AE6-5651022EAA94/Documents/images/86_2.png
[NSBundle mainBundle] is not suitable for loading the images because at runtime, the application tries to connect to the server to download the images, they are not static.
But loading the images from Documents/images folder does not give me the image on the TableView.
static NSString *CellIdentifier = #"CellCategory";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
UIImageView *imageView = cell.imageView;
MenuItem *item = (MenuItem *) [arrayMenuItems objectAtIndex:indexPath.row];
cell.textLabel.text = item.descrizione;
NSString *strImagePath = [[imagesFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%d_%d", item.idItem, item.idNode]] stringByAppendingPathExtension:#"png"];
NSLog(#"strImagePath: %#", strImagePath);
imageView.image = [[UIImage imageWithContentsOfFile:strImagePath] autorelease];
2010-01-22 17:07:42.842 Foo[2102:207] strImagePath: /Users/Hoang/Library/Application Support/iPhone Simulator/User/Applications/6133A161-F9DC-4C92-8AE6-5651022EAA94/Documents/images/86_2.png
Is there anyone having the same problem?
I have looked around in stackoverflow but have not succeeded.
Thanks in advance.
I've just had the same problem with loading images from application's Documents folder to UITableViewCell. This works:
[UIImage imageWithContentsOfFile:fullPath];
hardcoding the path is a bad idea since it can change during a redeploy,
try something like this..
NSString *imagessDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/images"];
and verify the file/image is even there with nsfilemanager
Edited: ANSWER
Be sure to check the response on NSData to see if there are images. In my case, all codes are ok, but the response from server give nothing. It is still able to save the image to the file on the documents/images folder, and still not raise any error, until I realized that all the images are not exist on the server. THAT WAS THE ERROR, not relates anything to the Documents folder
Original answer
There must be some problems with the initialization code of UIImage.
I have tried already three initialization functions for image having the path on the Documents directory.
But it just does not work.
Here you can see, the code always fall into the (exist) block, the first line is to load the image from the Documents/images directory, it always fails.
The second line inside the (exist) block, I tried to get the image from the bundle, it works perfect, but it is not what I want.
Fourth line of code, I get the original link of the images on the server and it gets what I nearly want. (Actually, what I want is to save all the images from the server into the Documents/images directory before hand, and then load them from there)
NSString *strImagePath = [[imagesFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%d_%d", item.idItem, item.idNode]] stringByAppendingPathExtension:#"png"];
NSLog(#"strImagePath: %#", strImagePath);
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:strImagePath];
if (exists){
//UIImage *menuImage = [UIImage imageWithContentsOfFile:strImagePath];
//UIImage *menuImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"ALT" ofType:#"png"]];
//imageView.image = menuImage;
NSString *strImagePathURL = [NSString stringWithFormat:#"http://foo.com/%d_%d.png", item.idItem, item.idNode];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strImagePathURL]];
imageView.image = [[UIImage alloc] initWithData:imageData];
}
else {
imageView.image = [UIImage imageNamed:#"ALT.png"];
}