create UiImage for image in www/Images folder - ios

I need to use images present in WWW/Images folder in my cordova iOs project. I am using cordova-2.3.0 and iOs 6 versions.
I tried to get image by below code but it is not working for images in WWW/Images folder, it is working fine for images present in resources folder.
UIImage *image = [UIImage imageNamed:#"Car_Main.png"];
How can I access Images present in WWW/Images folder.

I'm don't really understand, where is your WWW/Images folder. If in application directory - try this code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:#"/WWW/Images/Car_Main.png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:filePath];
If in project - maybe you forget to add your image to target resources?

// Save from documents
NSString* path = [NSHomeDirectory() stringByAppendingString:#"/WWW/Images/Car_Main.png.png"];
BOOL Done = [[NSFileManager defaultManager] createFileAtPath:path
contents:nil attributes:nil];
if (!Done) {
NSLog(#"Error creating file %#", path);
} else {
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
[myFileHandle closeFile];
}
// Get from documents
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];

Related

How to access a directory

I would like to save image in a folder. I already the code. to download and save image but I would like to know how to find the path of ma folder !
I create a directory in xcode but the images don't find it and there aren't image in it.
So, I would like to save images in "img_bkgrd" folder.
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:nil];
to use the image I use this method:
-(UIImage *) loadImage:(NSString *)fileName inDirectory:(NSString *)directoryPath{
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#", directoryPath, fileName]];
return result;
}
Can you send me the correct path ?
thanks
You can't save the images there. First of all, this is not actually a folder. It is called a group. It is a part of application bundle, which is readonly. You need to save data into Documents directory. Something like that:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *imageFolderPath = [documentsDirectory stringByAppendingPathComponent:#"/img_bckr"];
if (![[NSFileManager defaultManager] fileExistsAtPath:imageFolderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:imageFolderPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString* imagePath = [imageFolderPath stringByAppendingPathComponent:#"MyImage"];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:imagePath options:NSAtomicWrite error:nil];
You may store imagePath somewhere or build it later based upon file name and then simply:
UIImage* img = [UIImage imageWithContentsOfFile:imagePath];

save image to subfolder of /library/Application Support/bundleID_name/... iOS

The following code works without error or exception - but still, it does not do what it should ! I wanted to save an image into the iOS library/Application Support folder. More precisely, the image should be placed into a /library/Application Support/bundleID_name/subfolder/ (and the subfolder being called "location1").
If I check the functionality with the iOS-Simulator, I can see the creation of the subfolder (i.e. .../library/Application Support/bundleID_name/location1/). Also the function "saveImage" works without exception. But there is no image being saved !!!! (i.e.the image-file is missing and the folder remains empty) !!
What could be the mistake ??
Here is my code with the call of two functions (see code below):
UIImage *in_image = [UIImage imageNamed:#"template009c.jpg"];
NSString *locDirectoryName = #"location1";
NSURL *LocationDirectory = [self appendLocationToApplicationDirectory:locDirectoryName];
[self saveImage:in_image :#"image1" :LocationDirectory];
With the corresponding function-Nr1:
- (NSURL*)appendLocationToApplicationDirectory:(NSString*)locationDirName
{
NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager*fm = [NSFileManager defaultManager];
NSURL* dirPath = nil;
// Find the application support directory in the home directory.
NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
if ([appSupportDir count] > 0) {
// Append the bundle ID and the location-Foldername to the URL for the Application Support directory
dirPath = [[[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:appBundleID] URLByAppendingPathComponent:locationDirName];
// If the directory does not exist, this method creates it.
// This method call works in OS X 10.7 and later only.
NSError* theError = nil;
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError]) {
// Handle the error.
NSLog(#"%#", theError.localizedDescription);
return nil;
}
else {
// Mark the directory as excluded from iCloud backups
if (![dirPath setResourceValue:#YES
forKey:NSURLIsExcludedFromBackupKey
error:&theError]) {
NSLog(#"Error excluding %# from iCloud backup %#", [dirPath lastPathComponent], theError.localizedDescription);
}
else {
NSLog(#"Location Directory excluded from iClud backups");
}
}
}
return dirPath;
}
And function Nr2:
//saving an image
- (void)saveImage:(UIImage*)image :(NSString*)imageName :(NSURL*)pathName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *LocationDirectory = [pathName absoluteString];
NSString *fullPath = [LocationDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]];
/***** THE FOLLOWING LINE DOES NOT SEEM TO DO WHAT IT IS SUPPOSED TO *******/
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
/**** I also tried without the FileManager, but same problem - no file written... ***/
// [imageData writeToFile:fullPath atomically:NO];
NSLog(#"image saved");
}
By the way, getting the "fullPath" with the XCode-Debugger, I get:
"fullPath NSPathStore2 * #"file:/Users/username/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2BCC3345-9M55F-4580-A1E7-6694E33456777/Library/Application%20Support/bundleID_name/image1.png" 0x09d50950
Doesn't that also seem correct ?? But why is [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; not performing ???
This:
"fullPath NSPathStore2 * #"file:/Users/username/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2BCC3345-9M55F-4580-A1E7-6694E33456777/Library/Application%20Support/bundleID_name/image1.png" 0x09d50950
is not a valid path, it's a URL path but stored in a string. If you are going to use URL's then use ULRs rather than trying to convert to a string:
[imageData writeToURL:pathName atomically:YES];
(preferably naming the parameter as pathURL) and if you want to use paths then don't use a URL at any stage.
Also, where an API method returns an error or status flag, check it in the code as standard.
I'm pretty sure you can't save an image on a path you specify. You can save images on the gallery or in DocumentDirectory. This should be the code to save an image on the DocumentDirectory:
NSString *imgName=[#"imgname.png"];
[[NSUserDefaults standardUserDefaults]setValue:imgName forKey:#"imageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imgName];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];

Can't Reload UIImage from Saved file in iPhone Documents Directory location

I am making an app that will save a file to the iPhones Documents Directory and then when the View Controller is reloaded it will fetch it from that same location and display it. But it is not fetching it and displaying it.
I am using the following method to save the image:
void UIImageWriteToFile(UIImage *image, NSString *fileName)
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
}
I am trying to recall the image I have saved from the viewDidLoad method with the following code:
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = dirPaths[0];
NSString *fileName = [NSString stringWithFormat:#"/%#.png", self.fullname.text];
NSString *filePath = [documentDirectoryPath stringByAppendingString:fileName];
[self.imageView setImage:[UIImage imageNamed: filePath]];
However, it is not showing my image. Can anyone help me and tell me where I am going wrong please. I am new to iOS Development.
replace this line: [self.imageView setImage:[UIImage imageNamed: filePath]];
with this one :
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
[self.imageView setImage:image];
You can use [UIImage imageNamed:] with images from the Documents folder and have the benefits of the underlying caching mechanism, but the file path is slightly different.
Use the following:
NSString *fileName = [NSString stringWithFormat:#"../Documents/%#.png", self.fullname.text];
UIImage *image = [UIImage imageNamed:fileName];
You need to use method
- (UIImage*)initWithContentsOfFile:(NSString*)path
to init images from Documents or Cache directories.
imageNamed: is used for getting images from application bundle.

Managing files and directories in an app's Documents directory

I am trying to work out how to manage files and directories in my app's Documents folder. I have been trying to make sense of the NSData class but without joy. I have managed to write an image to my Documents folder using the following code.
- (IBAction)writeImage:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = [UIImage imageNamed:#"Default.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
What I would like to know is how to create and delete directories and files. Can anyone point me to correct place to look? Thanks in advance.
For folder you can use:
[[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
It will create all folders at given path which is cool :)
The NSFileManager class enables you to perform many generic file-system operations and insulates an app from the underlying file system.
There is a class method in NSFileManager class called +defaultManager which always gives you same FileManager object or shared Object and most file operations can be performed using this shared file manager object.
You can write by avoiding overwriting your file if it already exists as below and can also check if the folder is writable or not.
NSString *imageName = #"Default.png";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *savedImagePath = [NSString stringWithFormat:#"%#/%#", documentsDirectoryPath, imageName];
// Write only if file does not exist.
if (![[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
// Check if folder is writable
NSString *folderPath = #"someFolderPath";
if ([[NSFileManager defaultManager] isWritableFileAtPath:folderPath]) {
NSLog(#"Folder is writable");
}else {
NSLog(#"Folder is not writable");
}

Displaying Saved Images in iOS 5

I have an app that I am saving images to the NSDocumentDirectory. I can see that the path is being set correctly but when I try to retrieve them the NSData is null.
Here are some of my snippets..
NSData *imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myApp"];
//Create unique filename
CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef newUniqueIdString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
path = [path stringByAppendingPathComponent:(__bridge_transfer NSString *)newUniqueIdString];
path = [path stringByAppendingPathExtension: #"png"];
[imageData writeToFile:path atomically:NO];
[self showPhoto:path];
Then in my showPhoto method
NSData *pngData = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage imageWithData:pngData];
If I debug pngData it is 0 bytes but my path show what I think is the correct path?
Any way of debugging if the photo is actually on the phone? Im not sure if it is getting saved or not.
You can do something like this and check if the file exists first and use imageWithContentsOfFile: to retrieve it.
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:localFilePath];
bool fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if(fileExists == YES)
{
UIImage *_image = [UIImage imageWithContentsOfFile:localFilePath]
}
If the image is still empty then there is something wrong with your image.
If you running app in simulator you can find application files here: /Users/{user}/Library/Application Support/iPhone Simulator/5.0/Applications
If you debugging on iPhone you can use iExplorer to see files on iPhone.

Resources