I am using sqlite db to save image path of document directory. Here is my code:
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);
These code save the image in document directory and path in sqlite. Now I want to show image from documents directory to imageview. How to do that? Any idea?
sample code:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(void)loadimage{
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"your image-name"];
UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubView:myimage];
[myimage release];
}
NSString *str = [NSString stringWithFormat:#"%#.jpg",[YourImageArray objectAtIndex:imageCounter]];
or
NSString *str=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"YourImageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullImgNm=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:str]];
[ImageView setImage:[UIImage imageWithContentsOfFile:fullImgNm]];
Hope Your Helpfull
NSString *docDirPath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
NSString *filePath = [docDirPath stringByAppendingFormat:#"myFile.png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
[imageView setImage:image];
If the entire path is stored in the sqlite then you just need to use this
NSString *imapeFilePath = PATH_FROM_DATABASE;
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];
if the file name is stored in the database then use the following
NSString *imapeFilePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:YOUR_IMAGE_NAME];
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
if (sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
if(selectStmt == nil)
{
const char *sql = "insert into imagetb(imagename,image) Values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &selectStmt, NULL) != SQLITE_OK)
// NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
NSLog(#"%s",sqlite3_errmsg(database));
}
sqlite3_bind_text(selectStmt, 1, [#"test.png" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(selectStmt, 2, [data1 bytes], [data1 length], SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(selectStmt))
NSLog(#"get: %s",sqlite3_errmsg(database));
else
NSLog(#"scan data added");
}
//showimage
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from imagetb";// LIMIT 0,100 ";// where status = 1 ";
sqlite3_stmt *selectstatment;
if (sqlite3_prepare_v2(database, sql, -1, &selectstatment, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectstatment) == SQLITE_ROW)
{
NSString *getorgstrid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 0)];
NSLog(#"id->%#",getorgstrid);
[getid addObject:getorgstrid];
NSString *getorgstrname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 1)];
NSLog(#"name->%#",getorgstrname);
[getname addObject:getorgstrname];
NSData *getorgstrimage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstatment,2)length:sqlite3_column_bytes(selectstatment, 2)];
[getimage addObject:getorgstrimage];
}
}
sqlite3_finalize(selectstatment);
}
//[tblorgland reloadData];
UIImage *image1 = [UIImage imageWithData:[getimage lastObject]];
NSLog(#"image%#",image1);
[getImageview setImage:image1];
[pool release];
==============================================================================
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"image.sqlite"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
getid=[[NSMutableArray alloc]init];
getname=[[NSMutableArray alloc]init];
getimage=[[NSMutableArray alloc]init];
[self downloadimage];
[self makeDBCopyAsNeeded];
}
-(void)downloadimage
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://0.tqn.com/d/graphicssoft/1/7/g/A/5/psptubezdotcom_003.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png");
pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
img=[[UIImage alloc]initWithData:data1];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",docDir];
NSLog(#"jpegFilePath:%#",jpegFilePath);
data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
}
- (void) makeDBCopyAsNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
NSString *dbPath = [self getDBPath];
NSLog(#"%#",dbPath);
if (success)
{
NSLog(#"Database Success Created");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSLog(#"Database:->%s",sqlite3_errmsg(database));
}
}
It is not recommended to store the image data in the sqlite. But if you want to store the image data then use this link
Save image data to sqlite database in iphone
Hope this will helps you..
You better use caches to store your images, and use database to store their names or some unique id's
Just write following code in -(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo: if you are getting image from gallery or Camera otherwise skip code under if (imageData != nil) and just use below code to save image in sqlite
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);
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'm downloading the images from the online image for cache when offline. When I open application, The image was downloaded all completely before UIAlertView pop. It's finish incorrectly. I want to make the UIAlertView pop before images download. Here there are my code below.
- (void) operatePopupUpdating {
myAlert = [[UIAlertView alloc] initWithTitle:#"Updating database.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[myAlert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(myAlert.bounds.size.width / 2, myAlert.bounds.size.height - 50);
[indicator startAnimating];
[myAlert addSubview:indicator];
[self operateUpdate];
[self updateImage];
[self operationCompleted];
}
In updateImage, operateUpdate and operationCompleted Method
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:ico_path]];;
[thedata writeToFile:localFilePath atomically:YES];
}
}
-(void) operationCompleted
{
[myAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message form System" message:#"Database was updated successful" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (void)operateUpdate {
NSString *filePath = [self dataFileSettingPath];
int updatedVer = 0;
int version = [self checkDatabase];
if (version == -1) {
updatedVer = [self createDataBase:0];
} else {
updatedVer = [self updateDataBase:version];
}
[self.settingInfo setObject:[NSString stringWithFormat:#"%d",updatedVer] forKey:#"DBVersion"];
[self.settingInfo writeToFile:filePath atomically:YES];
}
How I fix them and work correctly?
The alertView will show only after your image downloading complete. One Solution to solve this is,
Create another class ImageDownLoad.h
in .h
#property(nonatomic,assign)id delegate;
#property(nonatomic,retain) NSString *path;
in .m
#synthesize delegate;
#synthesize path;
Create a method namely,
-(void)startDownloadImageWithUrl:(NSURL*)imageUrl withLocalFilePath:(NSSTring*)filePath{
path = filePath;
receiveData = [NSMutableData data];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:imageUrl];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receiveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[(id)delegate performSelector:#selector(SaveData:inFilePath:) withObject:receiveData withObject:path];
}
This will create connection and start download your image in a separate class. Then in your mai ViewController add bit of code like below.
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
ImageDownLoad *imageDown = [[ImageDownLoad alloc]init];
imageDown.delegate = self;
[imageDown startDownloadImageWithUrl:[NSURL URLWithString:ico_path] withLocalFilePath:localFilePath];
}
}
This method will be called each time when image download completes.
-(void)SaveData:(NSData*)data inFilePath:(NSString*)filePath{
[data writeToFile:filePath atomically:YES];
}
Your UI wont delay by doing so :)
-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet
I have this code:
#define ALERT(X) {UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info" message:X delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];[alert show];[alert release];}
- (id)readPlist:(NSString *)fileName {
NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"plist"];
plistData = [NSData dataWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
NSLog(#"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
[error release];
}
return plist;
}
- (void)writeToPlist: (NSString*)a
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"data.plist"];
NSMutableArray* pArray = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
[pArray addObject:a];
[pArray writeToFile:finalPath atomically: YES];
ALERT(#"finished");
/* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}
- (void)viewDidLoad {
[super viewDidLoad];
[self writeToPlist:#"this is a test"];
NSArray* the = (NSArray*)[self readPlist:#"data"];
NSString* s = [NSString stringWithFormat:#"%#",the];
ALERT(s);
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
On the simulator the second alert shows the content of the file correctly but on the device it shows nothing?? What's i'm doing wrong? Please show a code/snippet....
The problem is that you could not write a file into mainBundle folder, only Documents folder is accessable on your Device.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];