How to set button background from iphone documents folder - ios

I have image file which is stored in the iphone documents dir when i gave that image to button background it does not show.
NSString*imageThumbnailVideo= [NSString stringWithFormat:#"%#thumbVideo.png",imageThumbnail];
NSLog(#"imageThumbnailVide is %#",imageThumbnailVideo);
NSString * filePath = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(),imageThumbnailVideo];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists == 0)
{
NSLog(#"File is Not exists");
}
else
{
NSLog(#"File is present");
}
[thumbnailImageView setBackgroundImage:[UIImage imageNamed:imageThumbnailVideo] forState:UIControlStateNormal];
It also shows File is Present but does not display image.
Here is how i am saving the file
testT=[NSString stringWithFormat:#"%#thumbVideo",titleTextField.text];
NSString *newStringVT = [testT stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString*imageTitleVT=[NSString stringWithFormat:#"%#.png",newStringVT];
NSString *pathVT = [documentsDirectory stringByAppendingPathComponent:imageTitleVT];
NSData*thumbVideoData=UIImagePNGRepresentation(thumbnail);
NSError * error = nil;
[thumbVideoData writeToFile:pathVT options:NSDataWritingAtomic error:&error];

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *img_path = [documentsDirectory stringByAppendingPathComponent:#"YOUR IMAGE NAME.png"];
NSURL* uurl=[NSURL fileURLWithPath:img_path];
[thumbnailImageView setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:uurl]] forState:UIControlStateNormal];

You can obtain the image from a file by doing something like this:
UIImage* anImage = [UIImage imageWithContentsOfFile:validFilePath];
and then you can apply that image to a button like this:
[_someButton setImage:anImage forState:UIControlStateNormal];

Related

Save and load UIImageView

I want to save and load image in UIImageView
I have already tried some code but it doesn't work.
The Code i have tried:
Save:
UIImage *image = ...;
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];
Load:
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];
But these code doesn't work!
I hope you want to save image in document directory folder
here is the way to save image:
- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
to get image from document directory:
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Hope this will help
Globally declare imageView
UIImageView *imageView;//if u create imageView in interfaceBuilder. then u can replace this line by creating outlet of ur imageView
for loading image:
//Loading image in imageView
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"image.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachedImagePath])
{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:cachedImagePath]];
if (image)
{
imageView = [[UIImageView alloc]init];//Dont do this, if u created imageView using interFace builder
[imageView setFrame:CGRectMake(50, 100, 200, 200)];//Dont do this, if u created imageView using interFace builder
[self.view addSubview:imageView];//Dont do this, if u created imageView using interFace builder
[imageView setImage:image];
}
else
{
NSLog(#"Unsupported File");
}
}
else
{
NSLog(#"Image not Found in the path");
}
for saving image:
UIImage *image = imageView.image;
if (image)
{
NSString *cachedFolderPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *cachedImagePath = [cachedFolderPath stringByAppendingPathComponent:#"imageSaved.png"];
[UIImagePNGRepresentation(image) writeToFile:cachedImagePath atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachedImagePath])
{
NSLog(#"File Created");
}
}
else
{
NSLog(#"No image to save");
}

set an Image for a UIbutton from documents directory

I try to set an image for a UIButton from documents directory
i tried this:
-(IBAction) vignettesBank1:(id)sender {
NSString *localPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imageBouton1 = [localPath stringByAppendingPathComponent:[[NSString alloc]initWithFormat:#"btn01.png"]];
[boutonVideo1 setImage:[UIImage imageNamed:imageBouton1] forState:UIControlStateNormal];
NSLog(#"imageBouton1=%#",imageBouton1);}
log return :
imageBouton1=/var/mobile/Applications/164F9A40-10AF-402E-A46C-73084CAA8627/Documents/btn01.png
i try this too :
-(IBAction) vignettesBank1:(id)sender {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *pngfile = [documentsDir stringByAppendingPathComponent:#"btn01.png"];
[boutonVideo1 setImage:[UIImage imageNamed:pngfile] forState:UIControlStateNormal];
NSLog(#"imageBouton1=%#",pngfile);}
log return the same :
imageBouton1=/var/mobile/Applications/164F9A40-10AF-402E-A46C-73084CAA8627/Documents/btn01.png
my button doesn't load my image
thank's for your help
imageNamed: is for files in you bundle. You should use
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath: imageBouton1]];
[boutonVideo1 setImage:[[UIImage alloc] initWithData:pngfile] forState:UIControlStateNormal];

Store images in application

I've created folder called "Image store" using the following code. my requirment is i want to save images to the folder "Image store" on api success and the images should be saved in application itself not in database or photo album.I want to know the mechanism by which i can store images in application
-(void) createFolder {
UIImage *image = [[UIImage alloc]init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
else
{
}
}
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
{
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
u can do something like this
u can run a loop for images like this
//at this point u can get image data
for(int k = 0 ; k < imageCount; k++)
{
[self savePic:[NSString stringWithFormat:#"picName%d",k] withData:imageData];//hear data for each pic u can send
}
- (void)savePic:(NSString *)picName withData:(NSData *)imageData
{
if(imageData != nil)
{
NSString *path = [NSString stringWithFormat:#"/ImageStore/%#.png",pincName];
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,path]; //path means ur destination contain's this format -> "/foldername/picname" pickname must be unique
if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]])
{
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];
if(error)
{
NSLog(#"error in creating dir");
}
}
[imageData writeToFile:pngPath atomically:YES];
}
}
after successful download and saving u can retrieve images like below
- (UIImage *)checkForImageIn:(NSString *)InDestination
{
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,InDestination];//hear "InDestination" format is like this "/yourFolderName/imagename" as i said imagename must be unique .. :)
UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
if(image)
{
return image;
}
else
return nil;
}
link to find path
see this link to find the path ..
aganin do same this run loop like below
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
for(int k = 0 ; k < imageCount; k++)
{
UIImage *image = [self checkForImageIn:[NSString stringWithFormat: #"/yourFolderName/ImageName%d",k]];//get the image
[imagesArray addObject:image];//store to use it somewhere ..
}
Write this code after creating directory
NSString *path= [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
UIImage *rainyImage =[UImage imageNamed:#"rainy.jpg"];
NSData *Data= UIImageJPEGRepresentation(rainyImage,0.0);
[data writeToFile:path atomically:YES]
The document directory is found like this:
// Let's save the file into Document folder.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",docDir);
NSLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
Thats just a sample of the code provided which tells you where the correct path is to save in your ipone device.
Check the below blog post,it's step by step guide with source code .
Download an Image and Save it as PNG or JPEG in iPhone SDK

How can I make a folder in NSDocument directory where I can save all the photos and delete the data from same folder when I want?

I have a tableView where for each cell I'm getting an image url string and I'm saving all data in the NSDocument directory.
I want to store all the data in folder made in the NSDocument directory and I also want to delete all the contents in that folder later. How to do it?
this is the method I'm using
(void)setThumbnailTo :(UITableViewCell *)cell withRefString:(NSString *)string {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"patientPhotoFolder"];
NSString *imgPath = [string stringByReplacingOccurrencesOfString:#"amp;" withString:#""];
imgPath = [imgPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *key = [self sha1:imgPath];
NSString *fileToSave = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",key]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileToSave];
if (!fileExists)
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0ul);
dispatch_async(queue, ^{
NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgPath]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
NSData *jpegData = UIImageJPEGRepresentation(image,4);
[[NSFileManager defaultManager] createFileAtPath:fileToSave contents:jpegData attributes:nil];
dispatch_sync(dispatch_get_main_queue(), ^{
patientPhoto.image = image;
});
});
patientPhoto.image = [UIImage imageNamed:#"patientPhoto.png"];
}else{
UIImage *image = [UIImage imageWithContentsOfFile:fileToSave];
if(!image) image = [UIImage imageNamed:#"patientPhoto.png"];
patientPhoto.image = image;
}
}
How to lazily create a folder named "patientPhotoFolder" in your Documents directory (this could for example be a category on NSFileManager:
- (NSString *)pathToPatientPhotoFolder {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *patientPhotoFolder = [documentsDirectory stringByAppendingPathComponent:#"patientPhotoFolder"];
// Create the folder if necessary
BOOL isDir = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:patientPhotoFolder
isDirectory:&isDir] && isDir == NO) {
[fileManager createDirectoryAtPath:patientPhotoFolder
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
return patientPhotoFolder;
}
How to delete the contents of that folder (given you implemented it as a category on NSFileManager):
NSString *patientPhotoFolder = [[NSFileManager defaultManager] pathToPatientPhotoDirectory];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:patientPhotoFolder error:nil];
for (NSString *filename in contents) {
[[NSFileManager defaultManager] removeItemAtPath:[patientPhotoFolder stringByAppendingPathComponent:filename] error:NULL];
}

NSDocumentDirectory legal to save and load images on device?

The following code works on the simulator but crashes the device because img is nil:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (NSString* path in userImages) {
NSLog(#"image at %#", path); //logs "image at userImage0.png"
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:path];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
unichar ch = [path characterAtIndex:9];
NSLog(#"Ch = %c", ch); //correctly logs "0"
if (ch == '0') {
[self.images insertObject:img atIndex:0]; //this throws the error
}
}
Why is img nil when run on the device but not on the simulator? The image is originally saved like this:
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *imageName = #"userimage0.png";
NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
[UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];
Sorry, it was a capitalization problem. userimage vs userImage. The simulator doesn't care about that (I wish it did), but the device does.

Resources