The below code is not displaying the image which is downloaded from online and written into my application documents directory.
i have checked inside the iphone's simulator documents directory , the downloaded file is exist.
but the image is not displayed.
When trying to add a resources image using UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"]; , the uiimageview displays the image.bu the image which is downloaded from online and stored inside the app directory is not displaying the image.
Pls let me know and thanks
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
//--------------
UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[cell addSubview:imageView1];
}
try this ,this is perfectly working for me:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url1 = [NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:#"savedImage.png"];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath )
{
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubview:imageView1];
}
}
Instead of first converting the file to NSData, you can use
[UIImage imageWithContentsOfFile:filePath]
directly to load a image with given path.
Related
I'm new to iPhone development, I have used UIImagePickerController to capture the image manually, but i want to capture the image automatically, Is it possible to do that.
please help me.
Thanks in advance
Try This. In this I have saved the screen shot in photos album
-(void)screenShotCapture
{
//-- Screen Capture --------------------------------------------------------------------//
UIImage *image = nil;
UIGraphicsBeginImageContext(loginBgImgVw.frame.size);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(375, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:#"%#_Login_%#",providerIdStr,dateToday];
[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];
loginBgImgVw.frame = CGRectMake(10, 0, 1006, 669);
[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label removeFromSuperview];
//=--
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(#"path=--%#",paths);
NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:#"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
if ([screenCapturNameAry count] != 0)
{
if ([screenCapturNameAry containsObject:#"Login"])
{
[imageData writeToFile:savedImagePath atomically:NO];
}
}
UIImageWriteToSavedPhotosAlbum([self loadImage:#"Login_Provider"],self,#selector(image:didFinishSavingWithError:contextInfo:),NULL);
//--------------------------------------------------------------------------------------//
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error == nil)
{
NSLog(#"Login Image saved successfully.");
}
else
{
NSLog(#"Error occurred:%#",[error localizedDescription]);
}
}
You can get the saved image using following method
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
To take the screenshot you can use the following code.
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:#"screen.png" atomically:YES];
For Ratina display device you have to check:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);
I am trying to do download some images from server then , set these images as background image for some UIButtons .
so first downloading images :
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSString *str = [NSString stringWithFormat:urlMag1,urlMag2,nil];
NSData *data = [NSData dataWithContentsOfFile:str];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:path atomically:YES];
UIImage *imgMag1 = [UIImage imageNamed:#"i224_mag2.png"];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
but nothing happens !!,and how can I check to if these images are in directory to avoid more downloading
I would be grateful if you help me to solve this
thanks !
EDITED
#Fernando Cervantes
I created a method to set buttons BG images something like this , but I don't know why does not work !
- (UIImage *)loadImages :(NSString *)fileNames ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
[[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileNames, extension]]];
return 0;
}
and set BG images :
- (void)buttonsBGImage {
UIImage * bgMag2 = [self loadImages:#"i224_mag2" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[mag2 setBackgroundImage:bgMag2 forState:UIControlStateNormal];
}
but actually nothing happens ! even I check the file and it's in app directory
The following approach might help you out a bit.
Save
-(void) saveFile:(NSString *)fileName ofType:(NSString *)extension fromURL:(NSString *)fileIndexPath inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileIndexPath]];
[data writeToFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension] atomically:YES];
}
Check
-(BOOL) checkIfFileExists:(NSString *)fileName ofType:(NSString *)extension inDirectoryPath:(NSString *)directoryPath {
bool result;
if ([[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileName, extension]]]) {
result = TRUE;
} else {
result = FALSE;
}
return result;
}
Set
UIButton * button = [[UIButton alloc] init];
UIImage * backgroundImage = [self loadImage:#"YourImageName" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[button setImage:backgroundImage forState:UIControlStateNormal];
-Edited-
I believe your problem is that you are returning 0 in your loadImages method. Instead of returning the image itself.
This is how I accomplished it:
Load
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
[UIImage imageNamed:#"i224_mag2.png"]; // it is only for bundle. You should use
[UIImage imageWithContentsOfFile:path]
or
[UIImage imageWithData:data];
Update:
I use category for UIButton class.
- (void)loadImage:(NSString *)URL withActivityIndicator:(BOOL)hasActivity refreshObject:(UIView *)refresh{
// load image from cache cutted
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *loadedImage = [UIImage imageWithData:image];
// add image to cache cutted
[self setImage:loadedImage forState:UIControlStateNormal];
});
});
}
You are making NSData using dataWithContentsOfFile: API. you should use dataWithContentsOfURL instead.
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSData *image1 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]];
NSData *image2 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag2]];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
Usually [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]]; will freeze UI until image downloading complete.
This is driving me crazy!
I'm successfully saving a photo to my applications document directory from both the camera and if I choose an existing one from the camera roll. The code to do this is as follows. Note I know this part is working because in the simulator I can browse to the apps Documents folder and see the file being saved.
Example "save" code:
//Note: code above snipped to keep this part of the question short
case 1:
{
// select from library
NSLog(#"select from camera roll");
if([util_ isPhotoLibraryAvailable])
{
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
if([util_ canUserPickPhotosFromPhotoLibrary])
{
[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
}
controller.mediaTypes = mediaTypes;
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
}
} break;
//code below snipped out
And once the image is taken or selected:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(#"picker returned successfully");
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage])
{
UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *resizedImage = [util_ createThumbnailForImage:originalImage thumbnailSize:[util_ determineIPhoneScreenSize]];
NSData *imageData = UIImagePNGRepresentation(resizedImage);
NSString* imageName = #"MyImage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];
NSLog(#"fullPathToFile %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
// rest snipped out - at this point I see the image in the simulators/app/Documents directory
Now - the part that is NOT working (fetching and displaying the photo):
// code above snipped out (we're in tableView:cellForRowAtIndexPath)
imageButton_ = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 200, 200)];
NSString* imageName = [contentArray_ objectAtIndex:indexPath.row];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
SString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
UIImage *image = [UIImage imageNamed:fullPathToFile];
[imageButton_ setImage:image forState:UIControlStateNormal];
[cell addSubview:imageButton_];
NSLog(#"fullPathToFile: %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile: /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
return cell;
}
So, I get an empty button with no image displayed in the cell. I have also substituted the button for a UIImageView and still no luck...
Your problem is here:
UIImage *image = [UIImage imageNamed:fullPathToFile];
UIImage imageNamed: is only for images in the bundle. It doesn't work for images in the documents directory.
Try imageWithContentsOfFile: instead.
I am downloading a image from the url and saving it. When i try to display the same image in UI using ImageView I am not able to do it. So please suggest what changes I need to be done in the following code.
Thank you.
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.objectgraph.com/images/og_logo.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png::::%#", docDir);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSString *sss = [docDir stringByAppendingString:#"/test.png"];
imageView1.image = [UIImage imageNamed:sss];
NSLog(#"------%#",sss);
[image release];
}
UIImage *theUIimage = [UIImage imageNamed:sss];
image = [[UIImageView alloc] initWithImage:theUIimage];
[imageView1 addSubview:image];
How is your imageView initalized? Make sure to also specify the imageView.frame.
e.G.:
CGRect frame = CGRectMake(xPositionInView,yPositionInView,
image.size.width,image.size.height);
imageView.frame = frame;
I'm trying to get my memory management right and in the code below, if I include the final release statement (the one for filePath), it crashes and I can't see why. I've alloc'ed it, so why shouldn't I release it?
Further down, I return cellAbout to the TableView.
Can someone explain?
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
filePath = [filePath stringByAppendingString:#".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
[filePath release];
Many thanks,
Chris.
The answer is that the original filePath string IS alloced and needs to be released, but when you have the line:
filePath = [filePath stringByAppendingString:#".png"];
you create a different string - the original pointer to filePath is now gone and is a leak.
Here is the code you actually want
NSString *filePath = self.gem.poiType;
filePath = [filePath stringByAppendingPathExtension:#"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
So you don't need to release the filePath - it is auto released. Also apple has a special call for adding path extensions.
NSString *filePath = [self.gem.poiType stringByAppendingPathExtension:#"png"];
is actually how most people would write that code - one fewer lines.
Your Issues
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
Leaking filePath after this line.
filePath = [filePath stringByAppendingString:#".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
Releasing an autoreleased object after this line.
[filePath release];
Instead
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
NSString *extendedFilePath = [filePath stringByAppendingString:#".png"];
[filePath release];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: extendedFilePath];
imageView.image = image;
[image release];
[NSString stringByAppendingString] returns a NEW string, so that's where you're leaking your old one.
And then filePath is no longer owned by you, so when you release it later, you crash.
You could sidestep this whole thing like this:
NSString *filePath = [NSString stringWithFormat:#"%#.png",self.gem.poiType];// don't release me.
You are leaking here and later releasing an autoreleased string:
filePath = [filePath stringByAppendingString:#".png"];
If you really want to manually release, save the pointer:
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
NSString *somestring = [filePath stringByAppendingString:#".png"];
[filePath release];