iphone store image in application which are chosen from gallery - iphone

I searched a lot in google but not able to get the answer required. I am choosing photos from the image gallery and I want to store it in my application. If I have to store it in database(As BLOB), then I have to enter the name of the file(which I am not getting as I have chosen from the gallery). Can I store it anywhere else? please help. I am stuck in this from a long time. I need to extract the image and show it in map calloutview.
I am using the below code to choose photo from gallery and insert into the database
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)dictionary {
[picker dismissModalViewControllerAnimated:YES];
tempImg.image = image;
NSData *imgData = UIImagePNGRepresentation(tempImg.image);
NSLog(#"the img data %#",imgData);
sql = [NSString stringWithFormat:#"update latlng set image = '%#' where placeName = '%#'",imgData,pName.text];
The below code excuting the sql statement mentioned above
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement;
sqlStatement = [sql UTF8String];;
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
if (sqlite3_step(compiledStatement))
{
NSLog(#"YES");
}
}
else
{
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}sqlite3_close(database);
The below code to extract from database
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 5) length:sqlite3_column_bytes(compiledStatement, 5)];
the below code to display the image in callout
UIImageView *mapImg = [[UIImageView alloc] initWithImage [UIImageimageWithData:imgData]];
pinView.leftCalloutAccessoryView = mapImg;

Convert the image obtained for photo gallery to NSData and then save it in database as a Blob,So you can easily retrieve the nsdata from database when ever you needed.
NSData *image1Data = UIImagePNGRepresentation(image1.image);
sqlite3_bind_blob(init_statement, 1, [image1Data bytes], [image1Data length], NULL);
image1 is the ImageView where i am displaying the image from the photo gallery.
All the best.

You can use this to retrieve the path to a directory writable by your application:
NSString *directory = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
There are various ways to access that directory, including NSData's writeToFile: methods, the NSFileManager class, the NSFileHandle class, and even C stdio functions.

In my case i searching lots of google and then finaly got solution that below code its work's for me i hope its work for you
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(#"info: %#",info);
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirec = [paths objectAtIndex:0];
NSString *imgePath = [documentsDirec stringByAppendingPathComponent:#"note.sqlite"];
if(sqlite3_open([imgePath UTF8String], &database) == SQLITE_OK){
const char *sql = "insert into images (images) values (?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) == SQLITE_OK){
UIImage *edtedImae = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataForImage = UIImagePNGRepresentation(edtedImae);
sqlite3_bind_blob(addStmt, 1, [dataForImage bytes], [dataForImage length], SQLITE_TRANSIENT);
}
if(sqlite3_step(addStmt) != SQLITE_DONE){
NSLog(#"error %s",sqlite3_errmsg(database));
}
else {
NSLog(#"Insert row Id = %d",sqlite3_last_insert_rowid(database));
}
sqlite3_finalize(addStmt);
}
sqlite3_close(database);
[picker dismissModalViewControllerAnimated:YES];
}
thank you

Related

Save Image in SQlite Database in iOS which fetched from Gallery

I am try to fetch image from Gallery and save it to SQLite Database. so that i will use this image in other part of my Application. I am get image from Gallery and show it in imageView it works fine but when i try to save it in Database application crash. I am using following code to convert image in NSData and then save it to Database field which is BLOB in type.
NSData * imageData;
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
[picker dismissModalViewControllerAnimated:YES];
ImageView.image= img;
imageData= UIImagePNGRepresentation(_ImageView.image);
}
and My SQLite insert method is:
-(void) CreateGoal:(NSString *)Title :(NSString *) Description :(NSString *)NextStep :(NSString *) Date :(NSData *)image{
//Get list of directories in Document path
NSArray * dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Define new path for database
NSString * documentPath = [[dirPath objectAtIndex:0] stringByAppendingPathComponent:#"GoalBook.db"];
if(!(sqlite3_open([documentPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
return;
}else{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO createGoal(title, description, nextstep, date, image) VALUES ('%#','%#','%#', '%#', '%#')",
Title, Description, NextStep, Date, image];
const char *sql = [insertSQL UTF8String];
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
return;
}else{
if(sqlite3_step(sqlStatement)==SQLITE_DONE){
sqlite3_finalize(sqlStatement);
sqlite3_close(db);
}
}
}
}
I use use this method for save my Data like this:
[self.database CreateGoal:_Goaltitle.text :_goaldescription.text :_goalnext.text :getGoaldate :imageData];
I googled a lot to find an answer, but after experimenting a lot I gave up.
Can any one suggest what is wrong with this Please ?
Thanks in advance

problem in reading image from data base in iphone

hi i am able to store the image into database by using the following code.......
-(void)insertimages: (NSData *)image
{
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSUInteger len = [image length];
NSLog(#"data size is %d", len);
sqlStatement="insert into messages values(10,?)";
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
//sqlite3_bind_int(compiledStatement, 1, -1);
//sqlite3_bind_blob(updateStmt, 3, [imgData bytes], [imgData length], NULL);
sqlite3_bind_blob(compiledStatement, 1, [image bytes], [image length], SQLITE_TRANSIENT);
//sqlite3_bind_text(compiledStatement, 1, [SMSBody UTF8String],-1,SQLITE_STATIC);
if(sqlite3_step(compiledStatement) == SQLITE_DONE)
{
sqlite3_finalize(compiledStatement);
}
}
sqlite3_close(database);
}
}
but now my problem is i am not able to retrieve the image from the database and to display it in uiimageview...
con any one please help me how to do that.
Use following method to read the image data from database and stored the images in array or in dictionary
-(void) readImageDataFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the img Array
imageArray = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from messages";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]];
];
NSData *imgData = [NSData dataWithContentsOfURL: url];
// Create a new image object with the data from the database
iconImage.image=[UIImage imageWithData:imgData];
// Add the img object to the img Array
[imageArray addObject:iconImage];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
I was trying to do this a year ago, I wrote code to save the images into a sqlite3 db using osx sdk (of which i was able to write and read, i could even store the images in the db with ruby and read them on with macosx sdk). But when i moved this exact code over to an iOS app it would pull out bad data. If you do work this out i'd like to know the answer.

sqlite3 insert and read BLOB data in database

I need to read and write BLOB data to a database. Here is my structure table
#define CREATE_TABLE_USERS_SQL "CREATE TABLE IF NOT EXISTS %# ( \
UserID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \
Name VARCHAR(50), \
Image BLOB);"
How can I insert it into database, and then retrieve from it?
Environment: iPhone SDK 4.1 SQLite3 database.
This code fails:
NSData * buf2 = [[NSData alloc] init];
sqlite3_column_blob(statement, 5);
buf2 = sqlite3_column_bytes(statement, 5);
user.image = [UIImage imageWithData: buf2];
Thanx all!! With yours help I'v solved problem and want to share results for future beginners like I am.)
-(void) addToDB
{
NSLog(#"\nCreating db");
NSString *str = #"CREATE TABLE IF NOT EXISTS Images (image1 BLOB);";
int res = SQLITE_ERROR;
res = sqlite3_open([#"aa.sql" UTF8String], &database);
res = sqlite3_exec(database, [str UTF8String], NULL, NULL, NULL);
sqlite3_stmt *updStmt =nil;
const char *sql = "INSERT INTO Images (image1) VALUES (?);";
res = sqlite3_prepare_v2(database, sql, -1, &updStmt, NULL);
if(res!= SQLITE_OK)
{
NSLog(#"Error while creating update statement:%s", sqlite3_errmsg(database));
}
UIImage *img = [UIImage imageNamed: #"flower.png"];
NSData *imageData = [NSData dataWithData: UIImagePNGRepresentation(img)];
res = sqlite3_bind_blob(updStmt, 1, [imageData bytes], [imageData length] , SQLITE_TRANSIENT);
if((res = sqlite3_step(updStmt)) != SQLITE_DONE)
{
NSLog(#"Error while updating: %#", sqlite3_errmsg(database));
sqlite3_reset(updStmt);
}
res = sqlite3_reset(updStmt);
res = sqlite3_close(database);
}
-(void) readFromDB
{
NSLog(#"\nReading from db");
NSString *query = #"SELECT image1 from Images";
int res = SQLITE_ERROR;
int len = 0;
res = sqlite3_open([#"aa.sql" UTF8String], &database);
sqlite3_stmt *statement;
res = sqlite3_prepare_v2 (database, [query UTF8String], -1, &statement, nil);
if (res == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
len = sqlite3_column_bytes(statement, 0);
NSData *imgData = [[NSData alloc] initWithBytes: sqlite3_column_blob(statement, 0) length: len];
UIImage *img = [[UIImage alloc] initWithData:imgData];
self.view1.image = img;
}
}
sqlite3_finalize(statement);
res = sqlite3_close(database);
}
Apart from choosing your client or programming interface, usage does not differ from any other string field.
[Update] I haven't had the luck to develop for the iPhone yet, but I believe it's the same as any other SELECT or INSERT query. Make sure to encode the BLOB and enclose it with single apostrophes (') like strings.
why not use fmdb by Gus Mueller et al, of Flying Meat? http://flyingmeat.com/
https://github.com/ccgus/fmdb
If you find fmdb useful, go and buy one of the excellents apps of Flying Meat. VoodooPad or Acron.
//-----insert IMAGE
- (void)setImage:(UIImage *)theImage
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *insertProgrammeSql = #"INSERT INTO imageTable (imageName) VALUES (?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [insertProgrammeSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
NSData *imageData = UIImagePNGRepresentation(theImage);
sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
}
sqlite3_close(myDatabase);
// return YES;
}
}
//--------get image
-(UIImage *)getImage
{
UIImage *image = nil;
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *selectSql = #"SELECT image FROM imageTable";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [selectSql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
int length = sqlite3_column_bytes(statement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0 ) length:length];
image = [UIImage imageWithData:imageData];
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return image;
}
This code fails:
NSData * buf2 = [[NSData alloc] init];
sqlite3_column_blob(statement, 5);
buf2 = sqlite3_column_bytes(statement, 5);
user.image = [UIImage imageWithData: buf2];
You are calling the SQLite functions in the correct order. According to the SQLite docs:
The safest and easiest to remember policy is to invoke these routines
in one of the following ways:
sqlite3_column_text() followed by sqlite3_column_bytes()
sqlite3_column_blob() followed by sqlite3_column_bytes()
sqlite3_column_text16() followed by sqlite3_column_bytes16()
In other words, you should call sqlite3_column_text(),
sqlite3_column_blob(), or sqlite3_column_text16() first to force the
result into the desired format, then invoke sqlite3_column_bytes() or
sqlite3_column_bytes16() to find the size of the result. Do not mix
calls to sqlite3_column_text() or sqlite3_column_blob() with calls to
sqlite3_column_bytes16(), and do not mix calls to
sqlite3_column_text16() with calls to sqlite3_column_bytes().
However, buff2 is an integer, not a data pointer. sqlite3_column_bytes tells you how many bytes are in the blob.

How to use sqlite3_column_blob with NSData

How to use sqlite3_column_blob with NSData what parameter I need to pass
In my iPhone App I want to retrive image stored in NSData format in sqlite database in BLOB datatype
for retriving it
//select query
NSString *selectQuery = [NSString stringWithFormat:#"select image_column from tbl_image where id=1"];
NSArray *arraySelect = [database executeQuery:selectQuery];
//displaying image
NSData *imageData = [[arraySelect objectAtIndex:0] valueForKey:#"image_column"];
self.img3=[UIImage imageWithData:imageData];
imageView.image=img3;
from above code I am not able to display image
so please help and suggest
thanks
sqlite *database;
sqlite3_stmt *Stmt;
sqlite3_open([[self getDBPath] UTF8String],&database)
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"XXX.sqlite"];
}
NSData*thumbnailData;
//Inserting Thumbnail Data
NSString *lSQL = [NSString stringWithFormat:#"insert into Table(Thumbnail1) values(?)"];
if(sqlite3_prepare_v2(database, [lSQL UTF8String], -1, &Stmt, NULL) == SQLITE_OK)
{
sqlite3_bind_blob(Stmt, 1,[thumbnailData bytes], [thumbnailData length], NULL);
sqlite3_step(Stmt);
sqlite3_reset(Stmt);
if(Stmt)
sqlite3_finalize(Stmt);
}
//Fetching Thumbnail Data
NSString *lSQL = [NSString stringWithFormat:#"select Thumbnail1 from table"];
if(sqlite3_prepare_v2(database, [lSQL UTF8String], -1, &Stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(Stmt) == SQLITE_ROW)
{
NSString *myColNameNSString = [NSString stringWithFormat:#"%s", sqlite3_column_name(Stmt)];
if ([myColNameNSString isEqualToString:#"Thumbnail1"])
{
thumbnailData = [[NSData alloc] initWithBytes:sqlite3_column_blob(Stmt) length:sqlite3_column_bytes(Stmt)];
}
}
}
Hey, I don't what are your project requirements. I would not use BLOB unless it's required to.
reason is you are storing image file into sqlite, everytime you have to use the file you have access the database, process the file and use. which will be fairly easy and simple in terms of number of threads you are running if you use images directly form the disk. give a thought about it. Good Luck

Accessing an SQLite DB for two separate queries on iPhone App Initialization

I was successfully accessing my database to get a list of cities on the App launch. I tried running a second query against it right afterward to get the list of States but all that happens is that my app blows up with no usable error in the console (simply says "Program received signal: EXEC_BAD_ACCESS" and nothing more).
Here is the code, I was hoping someone could potentially explain to me what I'm doing wrong:
-(void) initializeDatabase{
// The database is stored in the application bundle
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mydatabase.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK){
[self initializeCities:database];
[self initializeStates:database];
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
}
-(void) initializeCities:(sqlite3 *)db {
NSMutableArray *cityArray = [[NSMutableArray alloc] init];
self.cities = cityArray;
[cityArray release];
// Get the primary key for all cities.
const char *sql = "SELECT id FROM my_table ORDER BY state";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW){
int primaryKey = sqlite3_column_int(statement, 0);
City *city = [[City alloc] initWithPrimaryKey:primaryKey database:db];
[cities addObject:city];
[city release];
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
}
-(void) initializeStates:(sqlite3 *)db {
NSMutableArray *statesArray = [[NSMutableArray alloc] init];
self.states = statesArray;
[statesArray release];
// Get the primary key for all cities.
const char *sql = "SELECT DISTINCT state FROM my_table ORDER BY state";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK){
// We "step" through the results - once for each row
while (sqlite3_step(statement) == SQLITE_ROW){
NSString *state;
state = (NSString *)sqlite3_column_text(statement, 0);
[states addObject:state];
[state release];
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
}
I can't debug this code as the debugger never hits my breakpoints at all.
If I remove the initializeStates method the app works as expected (albiet without a list of states).
You are releasing "state" without having allocated it. Try something like this:
while (sqlite3_step(statement) == SQLITE_ROW){
NSString *state = [[NSString alloc] initWithCString:(char*)sqlite3_column_text(statement, 0) encoding:NSASCIIStringEncoding];
//state = (NSString *)sqlite3_column_text(statement, 0);
[states addObject:state];
[state release];
}
Update: add cast above to fix compiler warning
Your problem is this:
NSString *state = (NSString *)sqlite3_column_text(statement, 0);
According to the documentation, sqlite3_column_text() returns a char*, not an NSString*.
Edit: You wouldn't have had this problem if you'd have used a wrapper ;)