hi Guys I have worked on Application and I am trying to Count the No of images in my resource folder and display no.of images in the Simulator
Could any body tll me how to do ?
give me code
If you want to do this, you'll need to use NSFileManager to look through the contents of [[NSBundle mainBundle] bundlePath] (the path of your app bundle) to find all the files with the right extension.
A better question: why do you want to do this?
Edit: alright, if you insist, you'll have to do something like this:
NSEnumerator *iter = [[NSFileManager defaultManager] directoryEnumeratorAtPath:[[NSBundle mainBundle] bundlePath]];
int count = 0; // number of images
for (NSString *path in iter) { // iterate through all files in the bundle
if ([[path pathExtension] isEqualToString:#"png"]) { // test if the extension is "png"
count++; // increment the number of images
UIImage *img = [UIImage imageWithContentsOfFile:path];
// do other things with the image
}
}
Related
Suppose, I have added one folder name "Images" in my project.How can I get the path to that folder? My main intention is to get the number of pictures in "Images" folder.
You should work a bit more on your question: it assumes a lot and requires the reader to guess.
I have added one folder name "Images" in my project
So I guess this means you added it as a folder reference
and I want to get it's path
And I guess that you want to do that at run time from your application, not at build-time from Xcode.
If so, you could do something like:
NSURL *containingURL = [[NSBundle mainBundle] resourceURL];
NSURL *imageURL = [containingURL URLByAppendingPathComponent:#"Images" isDirectory:YES];
NSFileManager *localFileManager = [[NSFileManager alloc] init];
NSArray *content = [localFileManager contentsOfDirectoryAtURL:imageURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants error:NULL];
[localFileManager release];
NSUInteger imageCount = [content count];
This code does not assume that all images are of the same kind.
[[[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"Images"] count];
This returns the number of jpg images from the Images folder. This is the case if you added the images to your application bundle.
- (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 got annoying question...
What if I have many image , and I want load it in to a table view
And show the file name as cell's text , and the preview image is also show in the cell.
When I select the cell , it will push to next view , show the big size image.
That's it .
I don't know how to load many folder to an array?
/*********** EDIT ***********/
This is the folder I set many images inside
You can see that's only one root folder ...
And this is my code to load the image inside
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Image"ofType:#""];
NSDirectoryEnumerator *direnum;
direnum = [fileManager enumeratorAtPath: filePath];
imageFolder = [NSMutableArray new];
for(NSString *filename in direnum){
if([[filename pathExtension] isEqualToString:#"png"]){
[imageFolder addObject:filename];
}
}
NSLog(#"Files in the folder %#",imageFolder);
I got result like this :
Files in the folder (
"macro1.png",
"macro10.png",
"macro11.png",
"macro12.png",
"macro13.png",
"macro14.png",
"macro15.png",
"macro16.png",
"macro17.png",
"macro18.png",
"macro19.png",
"macro2.png",
"macro20.png",
"macro21.png",
"macro22.png",
"macro23.png",
"macro24.png",
"macro25.png",
"macro26.png",
"macro27.png",
"macro4.png",
"macro5.png",
"macro6.png",
"macro7.png",
"macro8.png",
"macro9.png"
)
But what if I change the root folder like this
How to read the image files in the subfolders?
The App won't have issues finding files inside the bundle. The structure of your app development folders is irrelevant to the end product, for the most part. If you are storing the images in the apps bundle, the system can find it.
UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"imageName" ofType:#"png"]];
When I've had to do this as a quicky solution, I created an NSDictionary entry for each photo and stored that inside of an array in userPrefs. I programmatically created thumbnails for each image to utilize in the cell.imageView.image property, and then used an NSDictionary with #"description", #"imageName", and #"imageNameThumbnail" as the keys. You could do the same thing with an NSArray and just call the objectAtIndex, but I prefer the plain text friendliness of dictionaries.
You can try testing the path information that is being returned. Here are a couple of lines to try:
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"imageName" ofType:#"png"];
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"imageName" ofType:#"png" inDirectory:#"folderName"];
NSLog(#"Path 1: %#",path1);
NSLog(#"Path 2: %#",path2);
See what the output for these lines is, or if they return nothing.
Documents Directory as filePath
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
Then, enumerate the documentsDirectoryPath, and it should read subfolders recursively.
If it is local data you are using, you probably want to put the data in a .plist file. You would just be putting the names of the files in there, and then load the plist into an NSDictionary which you will only have one key for called "images" or something like that. You can then load all the objects under the "images" key into an array and use that array to populate your table.
Hope this makes sense.
i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);
I'm trying to populate an NSArray with a collection of images in Resources. However, for maximum flexibility, I'm trying to avoid hard-coding the filenames or even how many files there are.
Normally, I'd do something like this example from the sample code at apple:
kNumImages = 5; //or whatever
NSMutableArray *images;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", i];
[images addObject:[UIImage imageNamed:imageName];
}
However, I'm trying to avoid kNumImages entirely. Is there a way to run a regex or something on resources?
Here's a snippet that does just that from my iPhone app
// Load item icons
paths = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil];
for (NSString *filename in paths) {
filename = [[filename componentsSeparatedByString:#"/"] lastObject];
if ([filename hasPrefix:#"ItemIcon"]) {
[UIImage imageNamed:filename];
}
}
It loops through all resources that have a png extension, and it the filename begins with "ItemIcon" then it loads into UIImage's built in cache.
If you have them in a specific directory, you will need to specify the indirectory: argument.