I'm trying to change folderpath which saved image. (from myfolder to yourfolder)
My wrote code is like following.
When I execute following code, it's occurs error.
I think it's trying to load from folder before change.
How to load image file from changed folder?
Please help. :o
// image loading.
UIImage *image1 = [UIImage imageNamed:#"alarm.png"];
UIImageView *imageView1 = [[UIImageView alloc] initWithImage:image1];
imageView1.center = CGPointMake(100, 100);
[self.view addSubview:imageView1];
// get document path.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *appsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [appsDirectory objectAtIndex:0];
// create myFolder path.
NSString *myFolderPath = [documentPath stringByAppendingPathComponent:#"myFolder"];
if ([fileManager createDirectoryAtPath:myFolderPath withIntermediateDirectories:YES attributes:nil error:nil]){
NSLog(#"success");
}
else {
NSLog(#"failed");
}
// write image to saveImage#2x.png file.
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image1)];
NSString *saveName = #"saveImage#2x.png";
NSString *savePath = [myFolderPath stringByAppendingPathComponent:saveName];
[imageData writeToFile:savePath atomically:YES];
// load from saved the image1 to image2
UIImage *image2 = [UIImage imageWithContentsOfFile:savePath];
// change folderpath from myfolder to yourfolder
NSString *yourFolderPath = [documentPath stringByAppendingPathComponent:#"yourFolder"];
if ([fileManager moveItemAtPath:myFolderPath toPath:yourFolderPath error:NULL]){
NSLog(#"USER folder success");
}
else {
NSLog(#"USER folder fail");
}
// attach image2 to self.view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image2];
imageView.center = CGPointMake(100, 200);
[self.view addSubview:imageView];
// it's occurs error.
Following is log list.
2012-12-02 17:56:31.273 FolderTest[3372:11303] success
2012-12-02 17:56:31.277 FolderTest[3372:11303] USER folder success
ImageIO: CGImageRead_mapData 'open' failed '/Users/nice7285/Library/Application Support/iPhone Simulator/6.0/Applications/757CBD0E-CB49-4385-AF10-27322FB98381/Documents/myFolder/saveImage#2x.png'
error = 2 (No such file or directory)
ImageIO: CGImageRead_mapData 'open' failed '/Users/nice7285/Library/Application Support/iPhone Simulator/6.0/Applications/757CBD0E-CB49-4385-AF10-27322FB98381/Documents/myFolder/saveImage#2x.png'
error = 2 (No such file or directory)
am not really sure but i have some suggestions
try to change the create folder line to look like this
[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
use this function to write data
NSError *error;
[imageData writeToFile:savePath options:NSDataWritingAtomic error:&error];
i hope that help
This is not error of Not creating directories but this error occur because you save your image to sandbox without allocation
Solution:-
// write image to saveImage#2x.png file.
NSData *imageData = [[NSData alloc]initWithData:UIImagePNGRepresentation(image1)];
NSString *saveName = #"saveImage#2x.png";
NSString *savePath = [myFolderPath stringByAppendingPathComponent:saveName];
[imageData writeToFile:savePath atomically:YES];
and also fetch using allocated object ex.
// load from saved the image1 to image2
UIImage *image2 = [[UIImage alloc] initWithContentsOfFile:savePath];
Related
I have developed iOS App, in which i am downloading image from server and saving it in my Document directory.
But problem which i am facing is, sometimes my images getting corrupted when i download, even if the server response isSuccessful.
Here is my code snippet,
urlFile is path of UIImage which is on server e.g: www.abcd.com/images/pqr.jpg
fileName which i am using for saving image name in my DocDirectory.
- (void)downloadFile:(NSString *)urlFile withName:(NSString *)fileName
{
NSString *trimmedString = [urlFile stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"trimmedString=%#",trimmedString);
if ([trimmedString length]>0)
{
HTTPEaterResponse *response = [HTTPEater get:[NSString stringWithFormat:#"%#",trimmedString]];
if ([response isSuccessful])
{
NSLog(#"isSuccessful");
[self saveImage:[[UIImage alloc] initWithData:[response body]] withName:fileName];
} else {
NSLog(#"Url response failed %#", [response description]);
}
}
}
- (void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *data = UIImagePNGRepresentation(image);
NSLog(#"image =%#",image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
When i see my Log, it shows:
trimmedString= www.abcd.com/images/pqr.jpg
isSuccessful
image =null
Thanks in advance.
I use the following code and it works for me.
NSData *thumbImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]];
[thumbImageData writeToFile:cachedThumbnailFileName atomically:YES];
UIImage * image = [UIImage imageWithContentsOfFile:cachedThumbnailFileName];
imageView.image = image;
Hope it helps you. :)
To save image on directory use:
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.jpg"];
[UIImagePNGRepresentation(selectedImage) writeToFile:pngPath atomically:YES];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
have you logged the response [response body]?
Just try to convert that response as NSData and then save as image.
Using Base64Encoding class,you can convert the response as base64Data
NSData *imageData = [NSString base64DataFromString:[response body]];
[self saveImage:[[UIImage alloc] initWithData:imageData] withName:fileName];
i suggest yo use SDWebimage Class SDWebimage download.. i think its very helpful to you even i always prefer SDWebimage Library.
this are the some things.
An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
instead u can use, "NSURLRequest" and "NSURLConnection"
for example if u get image URL then,
NSURL* aURL = [NSURL URLWithString:trimmedString];//get the url of string
NSURLRequest *aReq = [NSURLRequest requestWithURL:aURL];
NSURLConnection *aConnection = [NSURLConnection connectionWithRequest:aReq delegate:self]; //get a connection to url , since it confirms to delegate u need to implement delegate methods
if(aConnection == nil) //if it is nil then cancel and close the request
{
aConnection = nil;
[aConnection cancel];
}
// after this implement this delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)received_data
{
if(image_data == nil) //if data is not initialised initialise it
{
image_data = [[NSMutableData alloc]init];
}
[self.image_data appendData:received_data];//append the received data
}
//this method is called after successful download of the image
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
// UIImage* sampleImage = [UIImage imageWithData:self.image_data];
// self.image = sampleImage; //convert the data to image
//since u hav complete downloaded date in "self.image_data"
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];//set the name of the image and path may it saving in application directory check it out
[self.image_data writeToFile:imagePath atomically:YES]; //saving the data with name
}
Hope this helps u :)
I am using using sqlite in my project
Previously I had saved image in data but now I am saving image in bytes like following code
NSUInteger len = [entObject.photoImageData length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [entObject.photoImageData bytes], len);
insertString = [NSString stringWithFormat:#"INSERT INTO TBL_COUNTDOWN (DAIRYID,EVENTID,DESCRIPTION,EVENTIMAGE) VALUES (\"%#\",\"%d\",\"No Data\",\"%s\")",self.dairyId,self.eventId,byteData];
For retrieving image I am using following code
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 3) length: sqlite3_column_bytes(statement, 3)];
NSLog(#"dataForCachedImage/getAllEvents is %#",dataForCachedImage);
UIImage *cachedImage = [UIImage imageWithData:dataForCachedImage];
NSLog(#"cachedImage/getAllEvents is %#",cachedImage);
For dataForCachedImage in NSLog I am getting data but for cachedImage I getting null
I dont no whats wrong in my code. Please help me
Thanks in advance
You can save image to document directory and store its path to sqlite database
save Image code is as follows
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
NSString *filePath= [NSString stringWithFormat:#"%#/%#.jpg", DOCUMENTS_FOLDER,caldate];
NSURL *url = [NSURL fileURLWithPath:filePath];
UIImage *image = [UIImage imageNamed:#"name.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
anytime you want to retrieve Image then get it then use following method to getImage
- (UIImage*)getImage
{
NSString *imagePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:#"imagename.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
return img;
}
deleting file
NSFileManager *fileManager=[NSFileManager defaultManager];
[fileManager removeItemAtPath:savedFilePath error:nil];
may this will help you..
So I have a function which gets an image from a URL which looks like this:
- (UIImage *) getImageFromURL:(NSString *)fileURL {
UIImage * result;
NSData * img_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:img_data];
return result;
}
and then a function which saves the image from a UIImage Which looks like this:
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:#"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
NSLog(#"Image named %# wrote to %#", imageName, directoryPath);
} else {
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
The issue I am facing is that when I run a UIImage through the saveImage function I dont think it is saving the image. This is because when I check for a UIImage imageNamed:#"Documents/filenamesavedas.jpeg" it returns (null). The image does however download correctly.
Here is my Documents Directory path function:
- (NSString *)getDocumentsDirectoryPath {
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(documentsDirectoryPath);
return documentsDirectoryPath;
}
Here is where I am downloading and trying to save the image:
dispatch_async(jsonQueue, ^{
// check to see if data authenticate runs successfully.
NSString *documentsDirectoryPath = [util getDocumentsDirectoryPath];
UIImage *imageToSave = [util getImageFromURL:[properties objectForKey:#"current_group_logoURL"]];
[util saveImage:imageToSave withFileName:[properties objectForKey:#"home_venue_logo"] ofType:#"jpeg" inDirectory:documentsDirectoryPath];
NSLog(#"Group Logo URL %#", [properties objectForKey:#"current_group_logoURL"]);
NSLog(#"Current Group Image %#", [properties objectForKey:#"home_venue_logo"]);
UIImage *testToSeeItHasDownloaded = imageToSave;
NSString *imageLocation = [documentsDirectoryPath stringByAppendingPathComponent:[properties objectForKey:#"home_venue_logo"]];
NSData *data = [NSData dataWithContentsOfFile:imageLocation];
UIImage *testToSeeImageHasSaved = [UIImage imageWithData:data];
NSLog(#"testToSeeImagehasDownloaded: %#", testToSeeItHasDownloaded);
NSLog(#"image location to save to: %#", imageLocation);
NSLog(#"testToSeeImagehasSaved: %#", testToSeeImageHasSaved );
});
The Console returns this:
2012-10-22 16:27:45.642 asdaf[46819:1d807] Group Logo URL http://somesite.com/50a0e42619424ba551a956511c098656.jpeg
2012-10-22 16:27:45.642 asdaf[46819:1d807] Current Group Image 50a0e42619424ba551a956511c098656.jpeg
2012-10-22 16:27:45.649 asdaf[46819:1d807] testToSeeImagehasDownloaded: <UIImage: 0xb09ed50>
2012-10-22 16:27:45.649 asdaf[46819:1d807] testToSeeImagehasSaved: (null)
testToSeeImagehasSaved should return null. But what am I doing wrong? Thanks.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//documentsDirectory is your documents directory path
//Now append your image name in this path
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"ImageName.jpeg"];
//convert your image in NSData
NSData *imageData = UIImagePNGRepresentation(image);
//Now write it at path
[imageData writeToFile:imagePath atomically:NO];
You can get this image in same way
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
Edit:
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [imageName stringByAppendingString:extension];
//Note extension should be like .png, .jpg, .jpeg dont forget dot (.).
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:imagePath atomically:NO];
}
Well i dont now about your whole code but why you're passing an UIImage object when you have to save your image in documents directory. You can pass NSData as well in your method. You're doing more.
Your problem is you're saving .jpg image each time and at the time of retrieving you're trying to find .jpeg image on same path thats why you're getting null value. See this line in your saving method -
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
this line doesn't look right to me:
UIImage *testToSeeImageHasSaved = [UIImage imageNamed: [#"Documents/" stringByAppendingString: [properties objectForKey:#"home_venue_logo"]]];
I think you have to do:
UIImage* image = [UIImage imageWithContentsOfFile:"YOUR_FILE_PATH"];
[UIImage imageNamed:"image_name"] is good only for images attached to your project
When you save it in the document folder, it does not exacly saves it in the "Document" directory but rather something like
path=/var/mobile/Applications/144B3628-5258-4939-8B80-006EC5BE45B2/Library/Caches/6_1.png
So to retreive your image you should use
NSString *uniquePath = [directory stringByAppendingPathComponent: filename];
image = [UIImage imageWithContentsOfFile: uniquePath];
where directory is the path you used to save it and filename the name of your jpeg.
[UIImage imageNamed:#"Documents/filenamesavedas.jpeg"]
Doesnt take paths it searches your bundle for the file with a specific name.
Locate the file using calls to NSFileManager and use the expected path and file name.
I need to check if an image exists in the project navigator. If it doesn't it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:#"23451.jpg"];
So I need to check if the image exists, if not download it. I tried to do this as followed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Set image
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"12345.jpg"];
//Check if the image exists at a given path
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
//If the image doesn't exists download it.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
If everything goes the right way the image is saved at the above path. But I still am not able to use this image with
[UIImage imageNamed:#"12345.jpg"];
I have got the feeling that i'm saving the images in a different directory than I should be saving them to.
Do you have any idea on how I should do this?
imageNamed will only work form image in the app bundle, not those stored in the Document directory. And you can't add the image to the app bundle, it readonly.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
There is no need to do this, you are now JPG a JPG:
if (!imageExists)
{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.mywebsite.com/12345.jpg"]];
[data writeToFile:imagePath atomically:YES];
}
NSData* data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:imagePath], 0.8)];
[data writeToFile:imagePath atomically:YES];
I did something similar .. here are some excerpts of the code .. not the complete code ...
- (void)loadAndStoreImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *theurlPortrait = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"portraitImageUrl"] ];
NSLog(#"Image url %# ",theurlPortrait);
imageDataPortrait = [NSData dataWithContentsOfURL:theurlPortrait];
[theurlPortrait release];
imagePortrait= [[UIImage alloc]initWithData:imageDataPortrait];
oldPathPortrait = [documentsDirectory stringByAppendingPathComponent:#"pt_wallpaper_1.png"];
NSURL *theurlLandscape = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"landscapeImageUrl"]];
imageDataLandscape = [NSData dataWithContentsOfURL:theurlLandscape];
[theurlLandscape release];
imageLandscape= [[UIImage alloc]initWithData:imageDataLandscape];
oldPathLandscape = [documentsDirectory stringByAppendingPathComponent:#"ls_wallpaper_1.png"];
[self replaceImages];
}
-(void)replaceImages{
//check if images were fully downloaded or corrupted.
if (isUserSignedIn) {
if (imageDataPortrait && imageDataLandscape) {
[UIImagePNGRepresentation(imagePortrait) writeToFile:oldPathPortrait atomically:YES];
[UIImagePNGRepresentation(imageLandscape) writeToFile:oldPathLandscape atomically:YES];
NSLog(#"IMAGES REPLACED");
NSDate *currentDate=[NSDate date];
[[ NSUserDefaults standardUserDefaults] setObject:currentDate forKey:#"previousDate"];
}
}
}
I am using a UIImagePickerController in my application.
After selecting an image by user,
image should be saved at application Documents Directory,
my Code is Give Below.
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissModalViewControllerAnimated:YES];
NSData *imgData = UIImagePNGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"]);
UIImage *img = [[UIImage alloc] initWithData:imgData];
stuImgView.image = img;
[img release];
//write image
NSString *imageFilename = [NSString stringWithFormat:#"%i.jpg", currentStudent.stuNo];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
UIImage *stuImg;
BOOL success;
NSFileManager *fm=[NSFileManager defaultManager];
// how to store file at documents dir????
}
i dont know how to use file manager to store a file?
Help me Out.
Thanks in advance.
You can use writeToFile:atomically::
[imgData writeToFile:path atomically:NO];