ios load an image from docDir into UIimagview - viewDidLoad - ios

I have a group of images saved in my DOcuments folder of the app. I got it to save to that location, I am having trouble loading from that location.
I got the UIimageView working hardcoded with images I dragged to a folder in the project with the code below in the viewDidLoad() method and when i ran the simulator it appeared.
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pants.png"]];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[self.view addSubview:bottomPic];
[bottomPic release];
However when I want to load the image from the Documents Directory nothing loads - Am confused and couldn't find any exact information to help me out on this situation.. This is currently what I have and when I run it doesn't throw any errors but no image appears. Am I missing something in my code? (I'm new to objective-c!)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"bottom1A2A6520-F556-436F-A1BC-D430223DC890-33098-00014708AE7E370F.png"]];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:path]];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[bottomPic setImage:image];
[self.view addSubview:bottomPic];
[bottomPic release];

A path is a path and an image is an image.
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:image];

Your code has a few issues. Try this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"bottom1A2A6520-F556-436F-A1BC-D430223DC890-33098-00014708AE7E370F.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:image];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[self.view addSubview:bottomPic];
[bottomPic release];
Unrelated to the problem, you were needlessly using stringWithFormat:.
The real problem was creating the UIImageView with an unneeded image using imageNamed:.
If this doesn't work then verify that path actually represents a file that really exists in the Documents folder. Verify image isn't nil.
Also consider use ARC (automatic reference counting) to make your life a lot easier.
Update: It appears you needed NSDocumentDirectory instead of NSDocumentationDirectory.

Related

Why is NSFileManager unable to find these png files?

I have written code to open image files after studying answers to the questions found here (a, b, c, d, e, f & g). But NSFileManager is unable to find them even though I added the png files to the project. I'm reasonably confident my code should be able to recognise either of the png files if they were in the right directory.
e.g.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"\ndirPaths %# \n\ndocsDir \n%#", dirPaths, docsDir);
NSString *imageFilePath = [docsDir stringByAppendingPathComponent:#"iTunesArtwork1024.png"];
NSLog(#"\n\nfile path should be \n\n%# \n\n", imageFilePath);
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageWithData:imageData];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
[self.view addSubview:logo];
}
But here is the log in the debug window
2017-07-14 18:26:35.679 IconShape[1089:348564]
dirPaths (
"/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents"
)
docsDir
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents
2017-07-14 18:26:35.679 IconShape[1089:348564]
file path should be
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents/iTunesArtwork1024.png
2017-07-14 18:26:35.679 IconShape[1089:348564]
Image file not found
Here is the state of the project after two png files were added.
Yet the log shows they are not visible to NSFileManager. So where would they be found ? i.e. what changes do I need to make to my code in order to find them ?
EDIT
This draft finds the png file following Subramanian's recommendation.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *imageFilePath = [[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
logo.image = image;
[self.view addSubview:logo];
}
The log now reads
Found file path : … .app/iTunesArtwork1024.png
and the image also appears in the subview.
__
Image is not in theDocument Directory, It's inside the bundle.
You have added the image files inside the project. But You are checking the image on Document Directory, Which is wrong. Image is inside app bundle.
You can simply assign the Image to UIImageView by the name of the image.
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
If you want to get the path of the image, then you have to use [NSBundle mainBundle]
[[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];
You can access images with names which are added in projects. Try with below code
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
The path where your are looking for the image is inside your device (real or simulator).
To load an image that is stored in your XCode project just do:
UIImage* image = [UIImage imageNamed:#"iTunesArtwork1024.png"];

how to load image to uiimageview

how to load image to uiimageview from a custom folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString*ext= [NSString stringWithFormat:#"/Imagenes/30775.png"];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:ext];
//option 1
UIImage * myImage = [UIImage imageWithContentsOfFile: dataPath];
_img.image = myImage
///option 2
UIImageView * myImageView = [[UIImageView alloc] initWithImage: myImage];
_img = myImageView;
///option 3
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:dataPath]];
_img.image = [UIImage imageWithData:imgData];
i try 3 options but not working
any idea ?
the image is loading from a custom folder
i checked the path and is correct but not load
Your path #"/Imagenes/30775.png" seems to be wrong. Double check it. Otherwise following should work
UIImage * myImage = [UIImage imageWithContentsOfFile: dataPath];
_img.image = myImage
NSString*ext= [NSString stringWithFormat:#"/Imagenes/30775.png"];
Your path is wrong.I guess the Imagenes is a group in your project. So xcode is not create a folder in your project main folder. The groups is only helps you to view the files easily in the xcode program.
Also you don't need stringWithFormat.
Try this;
NSString*ext= #"30775.png";

Loading from file not working.

I'm taking screenshots and writing them to file with this code:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directories objectAtIndex:0];
NSString *key = [documentsDirectory stringByAppendingPathComponent:#"screenshots.archive"];
NSMutableArray *storageArray = [NSMutableArray arrayWithContentsOfFile:key];
if(!storageArray)
storageArray = [NSMutableArray arrayWithObject:data];
else
[storageArray addObject:data];
[storageArray writeToFile:key atomically:YES];
When i load the images again i do this:
pics = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath]];
ScreenshotViewController *scv = [[ScreenshotViewController alloc]init];
[[self navigationController]pushViewController:scv animated:YES];
NSInteger row = indexPath.row;
[scv setImage:[pics objectAtIndex:row]];
dataFilePath method:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"screenshots.archive"];
}
The problem is that that the UIImageView, in the ScreenshotViewController remains blank. I have tested all kinds of things, and it is something about the way the images get saved/loaded into the array, but i'm not sure. I have also tested that the actual screenshot part is working by putting it into a UIImageView right away and adding it to the view.
NOTE:
If i change this
[scv setImage:[pics objectAtIndex:row]];
to this
[scv.myUIImageView setImage:[pics objectAtIndex:row]];
i get this exception: [__NSCFData _isResizable]: unrecognized selector sent to instance 0x847a280.
Whats the correct way of setting the image by?
Wow it got abit messy, hope its readable.
At first glance, and assuming your read/write code is correct, you are saving the image with PNG representation.
Thus, when reading, you will need to create a UIImage like this:
UIImage * myPic = [UIImage imageWithData:[pics objectAtIndex:row]];
Then try showing that image

Resizing an image from UIImagePickerController not working

I am following this post on how to resize an image. I placed the + (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize; in selectExerciseImageViewController.h and copied the relevant code to selectExerciseImageViewController.m.
Then I attempt to resize the image, save it, and retrieve the saved image file into a UIImageView. but for some reason the image is never showing the the UIImageView and the last NSLog returns null
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage* newImage = [selectExerciseImageViewController imageWithImage:[info objectForKey:#"UIImagePickerControllerOriginalImage"]
scaledToSizeWithSameAspectRatio:CGSizeMake(40.0,40.0)];
NSData* imageData = UIImagePNGRepresentation(newImage);
// Give a name to the file
NSString* imageName = #"MyImage.png";
// Now, we have to find the documents directory so we can save it
// Note that you might want to save it elsewhere, like the cache directory,
// or something similar.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
// and then we write it out
[imageData writeToFile:fullPathToFile atomically:NO];
//imageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
_testimg.image = [UIImage imageNamed:#"MyImage.png"];
NSLog(#"asd %#",[UIImage imageNamed:#"MyImage.png"]);
}
[UIImage imageNamed:#"MyImage.png"];
This loads an image from the main application bundle. You are writing the file to the documents directory. You need to instantiate the UIImage object with a different method. Try:
[UIImage imageWithContentsOfFile:fullPathToFile];

How to display an UIImage in a custom cell

I am trying to display an Logo image in my custom cell, from amazon Amazon S3 bucket though StackMob
but its not showing. if l paste the direct url path to the image it works, how do i get around this.
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
CGRect imageFrame = CGRectMake(2, 2, 67, 67);
self.customImage = [[UIImageView alloc] initWithFrame:imageFrame];
NSURL* imageURL = [NSURL URLWithString:[object valueForKey:#"restoLogo"]];
NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
self.customImage.image = tmpImage;
[cell.contentView addSubview:self.customImage];
the image is at this path [object valueForKey:#"restoLogo"] now returns the s3 url for the data.
If you are not using NSString's instance method
stringByAddingPercentEscapesUsingEncoding:
that could be the issue.
For example
NSString *escapedString = [imgURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Then turn it into a URL and continue on your way.

Resources