how to load image from subfolder of resources - iphone

hi i created a new group in my code and put the all images in that now resources\CountryFlags is the path i am doing this
NSString *fileName = countryInfo.ImageUrl;
CCSprite *flag ;
NSString * fullPath = [[NSBundle mainBundle] pathForResource: [fileName stringByDeletingPathExtension]
ofType: [fileName pathExtension]
inDirectory: #"CountryFlags"];
if (fullPath)
{
UIImage *theImage = [UIImage imageWithContentsOfFile: fullPath];
if (theImage)
{
flag = [CCSprite spriteWithCGImage: [theImage CGImage] key: fileName];
flag.position = ccp(200, 265);
flag.scale = .255;
}
}
but fullpath always got nil and not getting the code so any one have any idea how to solve this

I think it's because there is no "CountryFlags" folder in your app's bundle. XCode does not copy directory structure of resources unless folders are added as folder references (blue folder icons in project navigator, not yellow).

Related

Accessing the image which is in external bundle

I created a bundle with name applausible.bundle, i placed the bundle in supporting files.This is my code
NSBundle* myBundle;
myBundle = [NSBundle bundleWithPath:#"/Library/applausible.bundle"];
NSString *path = [myBundle pathForResource:#"splash.png" ofType:nil];
[imageName setImage:[UIImage imageNamed:path]];
Here I am unable to display the image on the image view. Another way I tried like this I place the image on the image view using xib,while running the app. The output is coming like this in console
Could not load the "splash_screen high resolution.png" image referenced from a nib in the bundle with identifier "com.xxxxxxx.ImageSample". Can any one tell me where i made a mistake.Finally my goal is to display the image on the UIImageview which is in external bundle.
This may help you.
NSString bundlePath = [[NSBundle mainBundle] pathForResource:#"applausible" ofType:#"Bundle"];
NSLog(#"Bundle path is %#",bundlePath);
NSBundle myBundle;
myBundle = [NSBundle bundleWithPath:bundlePath];
NSString *path = [myBundle pathForResource:#"splash_screen high resolution" ofType:#"png"];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
[imageName setImage:image];
please try it out.
It may be helpful
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"applausible" ofType:#"Bundle"];
using this method you can get the bundle path.Then use your code from second line
myBundle = [NSBundle bundleWithPath:bundlePath];
NSString *path = [myBundle pathForResource:#"splash" ofType:n#"png"];
[imageName setImage:[UIImage imageNamed:path]];

Reading Image from the Local Folder in Objective C

I need to Read a Image from the specific URL .
It works fine with WWW . but it returns a nil when the URL pointing the Local Folder .
// Works
NSString *sampleData = #"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg";
// Returns nil
NSString *sampleData = #"USER/user2/...";
Note :
I am changing the NSString to NSURL and creating the UIImage .
NSURL *url = [NSURL URLWithString: data];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
You are supplying a relative pathname for the file URL. That relative pathname is interpreted relative to the current working directory of the running application, which isn't guaranteed to be anything in particular, and so is almost certainly not what you want.
You can either supply an absolute path - one that starts with '/' - or set your app's current working directory to something explicit, like your user's Documents folder.
you probably should have a look into the NSBundle Class.
Methods like
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
or
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
is probably what you want
First of all, you can NOT read file from such path you given: "USER/user2/...", the file must in your App bundle or in your App's sandbox.
Second, check your path string if there was some texts need to be encoded in URL. Try:
NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Also, if the url is not nil, you should also check if your [NSData dataWithContentsOfURL:url]; is returning nil. If so, it means your URL is not correct so the method cannot find your file.
P.S., You are mistyping your image create code, you should call alloc before imageWithData:.
You should do something like to get the local url :
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, nameOfFile];
and finaly, load your image :
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
Try these instead
NSString *path = #"USER/user2/.../xxx.xxx";
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isFileExist = [fileManager fileExistsAtPath:path];
UIImage *image;
if (isFileExist) {
image = [[UIImage alloc] initWithContentsOfFile:path];
}
else {
// do something.<br>
}

Read Image file from custom directory using NSBundle

Creating a custom directory which has all the images. Designing it custom because, it will help me to get the images as an when I need at various places in the configuration.
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
[filemgr createDirectoryAtPath: #"/Users/home/lifemoveson/test" withIntermediateDirectories:YES attributes: nil error:NULL];
I have placed images under test folder and are of .png types.
Is there a way to retrieve the images like below.
/** UPDATED again **/
Currently this folder is under Application_Home/Resources/ImageTiles/ as per Photoscroller example.
How can we change it to /Users/home/lifemoveson/test/ImageTiles/ folder ?
- (UIImage *)tileForScale:(CGFloat)scale row:(int)row col:(int)col
{
// we use "imageWithContentsOfFile:" instead of "imageNamed:" here because we don't want UIImage to cache our tiles
NSString *tileName = [NSString stringWithFormat:#"%#_%d_%d_%d", imageName, (int)(scale * 1000), col, row];
// Currently this folder is under <Application_Home>/Resources/ImageTiles/ as per Photoscroller example.
// How can we change it to /Users/home/lifemoveson/test/ImageTiles/ folder ?
NSString *path = [[NSBundle mainBundle] pathForResource:tileName ofType:#"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
}
Applications running on iOS are sandboxed; you can't simply create directories wherever you please. Your createDirectoryAtPath: call will fail. You should use one of the directories set aside for your application instead.
Once you obtain the path for one of those directories, getting the path for files within them is simply a case of using NSString's stringByAppendingPathComponent: method.
Makin a call to the functions such as
NSString* newDirPath = [self createDirectoryWithName:#"Test"];
if (newDirPath) {
[self saveFile:#"MasterDB.sqlite" atPath:newDirPath];
}
which are implemented as follows
-(NSString*)createDirectoryWithName:(NSString*)dirName{
NSArray* directoryArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask , YES);
NSString* directoryPath = [directoryArray objectAtIndex:0];
NSString* newPath = [directoryPath stringByAppendingString:[NSString stringWithFormat:#"/%#",dirName]];
NSFileManager *filemamager = [NSFileManager defaultManager];
BOOL flag = [filemamager createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes: nil error:NULL];
return flag == YES ?newPath: nil;
}
-(BOOL)saveFile:(NSString*)fileName atPath:(NSString*)path{
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the File and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the File has already been created in the users filesystem
NSString *filePath = [path stringByAppendingPathComponent:fileName];
success = [fileManager fileExistsAtPath:filePath];
// If the File already exists then return without doing anything
if(success) return YES;
// If not then proceed to copy the File from the application to the users filesystem
// Get the path to the database in the application package
NSString *pathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
// Copy the database from the package to the users filesystem
NSError *error = nil;
BOOL flag = [fileManager copyItemAtPath:pathFromApp toPath:filePath error:&error];
return flag;
}
might help you solve your problem. Creating a directory is achieved using first function and the second will let you save files from your application bundle to any of the previously created directory. I hope you can modify it save files located at places other than Application bundle to suit to your need.

UIImageView - Displaying an image from Directory

I have the following code in place:
- (void)viewDidLoad {
NSString *homeDirectoryPath = NSHomeDirectory();
NSString *imagePath = [homeDirectoryPath stringByAppendingString:#"/graph.png"];
NSLog(#"Image: %#", imagePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath isDirectory:NULL])
{
graph = imagePath;
//[[NSFileManager defaultManager] createDirectoryAtPath:imagePath attributes:nil];
}
'graph' is defined as UIImageView. I'm trying to display the file in the path 'imagePath'. I know the code graph = imagePath is not correct, as the variable 'imagePath' states it contains the path to the image.
How would I display my image located at the specific image path ?
Regards,
Stephen
You'll have to create an imageview object, set it as the image view's image and release the image you created:
UIImage *graphImage = [[UIImage alloc] initWithContentsOfFile: imagePath];
graph.image = graphImage;
[graphImage release];

pathForResource? without using extension (Iphone)

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.