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..
Related
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];
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 create the one application in that create the locally store the file in payment while the application not be deleted.
This I have done: I download the file and store into locally (applications document folder).
Now I am having trouble with this:
While the after the image is downloaded then I fetch into locally and that image will not display. In NSLog following url is generated and i can't display the image.
/Users/username/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/F233ED88-1546-4FB0-BE93-0E0FB8C8C3D6/Documents/NationalMedalofArts-150x150.jpg
Edit:
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#",
#"/Users/username/Library/Application Support/iPhone Simulator/5.0/Applications/F233ED88-1546-4FB0-BE93-0E0FB8C8C3D6/Documents/NationalMedalofArts-150x150.jpg"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSLog(#"%#",imageData);
UIImage *image = [UIImage imageWithData:imageData];
self.imgView.image = image;
when the NSLog the NSData then it's NULL to display
This is better:
NSString *fileName = #"NationalMedalofArts-150x150.jpg";
NSString *path = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(), fileName];
self.imgView.image = [UIImage imageWithContentsOfFile:path];
Try using this:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:#"NationalMedalofArts-150x150.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:file];
UIImage *image = [UIImage imageWithData:imageData];
self.imgView.image = image;
When accessing files in the documents-folder of the application, which is where images and those sorts of things are found, you must use the first line to find the path to the documents-folder. The code above should work for you.
I want to get images in document directory folder.
I am using this code.
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
for(int i=0;i<[imagepath count];i++)
{
NSString* documentsDirectory = [path objectAtIndex:0];
NSURL *img = [NSURL URLWithString:[imagepath objectAtIndex:i]];
//here imagepath is array in that i get the url of image.
//here when i print the img data i got url from where i have to get images.
NSData *data = [NSData dataWithContentsOfURL:img options:NSDataReadingMapped error:nil];
//here when i put NSLog i get the null.
NSString *fullImagePath1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"image%d.png",i]];
[newreturnImage addObject:fullImagePath1];
[data writeToFile:fullImagePath1 options:NSDataWritingAtomic error:nil];
}
I can't get images in document directory folder.
What could be wrong with this code?
Try this code,
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", docDirectory,#"myimage.png"];
UIImage *cellImage=[UIImage imageWithContentsOfFile:filePath];
UIImageView *temp=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
temp.image=cellImage;
[myView addSubview:temp];
[temp release];
Updated :
NSData *myData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myURL]];
UIImage *myImage = [[UIImage alloc] initWithData:myData];
This link may help you. In the link James Webster has provided an excellent method which suits your requirement. If this does not help you. The code below that would definitely work for you as it works for me.
How save images in home directory?
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
for(int i=0;i<[imagepath count];i++)
{
NSString* documentsDirectory = [path objectAtIndex:0];
NSURL *img = [NSURL URLWithString:[imagepath objectAtIndex:i]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:img];
NSString *fullImagePath1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"image%d.png",i]];
[newreturnImage addObject:fullImagePath1];
[data writeToFile:fullImagePath1 options:NSDataWritingAtomic error:nil];
}
Hope this helps you.
Thanks.
I am saving the images when there is internet connection in my iphone.
Now i want to load the images which are saved in documents directory. I am getting the path, but the image is not displaying. Please help me in this.
Thanks in advance.
Here is my code:
+(UIImage *) getImagewithName:(NSString*) imagepath
{
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *gimage=[UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#",docDir,imagepath]];
NSLog(#"%#/%#",docDir,imagepath);
return gimage;
}
+(void)DownloadImage:(NSString*)ImagePath {
if ([ImagePath isEqualToString:#""])
return;
UIImage *dimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:/uploads/%#",ImagePath]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"pathIMAGEPATHS:::::::%#",ImagePath);
NSLog(#"path:::::::%#",docDir);
NSArray *patharr=[ImagePath componentsSeparatedByString:#"."];
NSString* Ext=[NSString stringWithFormat: #"%#",[patharr objectAtIndex:1]];
NSString *FilePath = [NSString stringWithFormat: [NSString stringWithFormat:#"%#/%#",docDir,ImagePath]];
if([Ext isEqualToString:#"png"])
{
NSLog(#"saving png");
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
else if([Ext isEqualToString:#"jpeg"])
{
NSLog(#"saving jpeg");
//NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(dimage, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:FilePath atomically:YES];
}
else
{
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
NSLog(#"saving image done");
[dimage release];
}
viggio24 makes a good point. But moreover, this code seems incredibly complicated to do something incredibly simple. Why do you download to data, then turn it into an image, just to turn it back into data, and finally write it? And then you read it again and make a new image? Why not just download the file to disk and read it? UIImage will do all the work of managing PNG and JPEG for you. Something like:
+(void)downloadImage:(NSString*)imagePath {
if ([imagePath isEqualToString:#""])
return;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[#"http://110.234.132.132/MBCMcAdmin/uploads" stringByAppendingPathComponent:imagePath]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:[docDir stringByAppendingPathComponent:imagePath] atomically:YES];
}
This is still a horrible idea in most cases, though, since it blocks the calling thread. It's better to do this with NSURLDownload which will do it all for you in the background and tell you when it's done.
I'd simplify the code, and then follow viggio24's comments, making sure that you error check this stuff. You're probably just not reading the file correctly or failing to write it.