Save Image Data to SQLite Database in Iphone

How to store image in sqlite database in iphone?

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..

Saving image from UIImagePicker to Sqlite DB

In your case your getting image from UIImagePicker successfully and converting it into NSData to be stored in sqlite, the only problem your facing is storing the NSData into sqlite.

Saving NSData into sqlite database requires it to be saved as bytes in sqlite, so either you store NSData in bytes or convert it into Base64 string and then strore the Base64 string in sqlite.

To store NSData in sqlite as bytes you can refer below links:

1) How to retrieve string from NSData stored in sqlite?

2) Retrieve nsdata from sqlite stored in Blob data type for iPhone App

To store NSData in sqlite as Base64 you can use below Base64 library which is very easy to use.

https://github.com/nicklockwood/Base64

Now to convert a NSData to Base64 just use below code:

NSString *aStrData = [theNSDataObject base64EncodedString];

And then after you fetch it from database convert back the Base64 string to NSData like below:

NSData *theNSDataObject = [aStrData base64DecodedData];

I prefer using Base64 string is a good way, so if in future if you want to send the image to any web service you can send it in base64 format also.

Storing and Retrieving Image in Sqlite with swift

Image itself cannot be stored into a database columns but you can first convert it into a string and then store it. The string is called base64 string. As far as I know, any image can be converted to that and reversely.

To encode to base 64:

let image : UIImage = UIImage(named:"imageNameHere")!
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

Now your UIImage object is converted to a String! Save strBase64 to SQLite DB. Remember to use text as column type because this string is very long.

To decode back to UIImage:

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!

Saving and retrieving images to and from SQLite in iOS


- (void)saveImage 
{
sqlite3_stmt *compiledStmt;
sqlite3 *db;
if(sqlite3_open([dbPath UTF8String], &db)==SQLITE_OK){
NSString *insertSQL=@"insert into Image(image) VALUES(?)";
if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK){
UIImage *image = [UIImage imageNamed:@"vegextra.png"];
NSData *imageData=UIImagePNGRepresentation(image);

sqlite3_bind_blob(compiledStmt, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);

if(sqlite3_step(compiledStmt) != SQLITE_DONE ) {
NSLog( @"Error: %s", sqlite3_errmsg(db) );
} else {
NSLog( @"Insert into row id = %lld", (sqlite3_last_insert_rowid(db)));
}

sqlite3_finalize(compiledStmt);
}
}
sqlite3_close(db);
}

- (void)showImage
{
sqlite3_stmt *compiledStmt;
sqlite3 *db;
int i = 1;
if(sqlite3_open([dbPath UTF8String], &db)==SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:@"Select image from Image Where Id = %d",i];
if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStmt) == SQLITE_ROW) {

int length = sqlite3_column_bytes(compiledStmt, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length];

NSLog(@"Length : %d", [imageData length]);

if(imageData == nil)
NSLog(@"No image found.");
else
imgView.image = [UIImage imageWithData:imageData];
}
}
sqlite3_finalize(compiledStmt);
}
sqlite3_close(db);
}

Store images in to sqlite database

For saving image to documents

- (void)saveImage:(UIImage *)image forPerson:(NSString *)fullName  {
// Make file name first
NSString *filename = [fullName stringByAppendingString:@".png"]; // or .jpg

// Get the path of the app documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// Append the filename and get the full image path
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:filename];

// Now convert the image to PNG/JPEG and write it to the image path
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];

// Here you save the savedImagePath to your DB
...
}

So, you later can get the image by

- (UIImage *)loadImage:(NSString *)filePath  {
return [UIImage imageWithContentsOfFile:filePath];
}

Save image data to sqlite database in iphone

Here is how you can Save image to SQLITE:

// Create Images Table.
sql_stmp = "CREATE TABLE IF NOT EXISTS IMAGES (URL TEXT UNIQUE, IMAGE BLOB)";
if( sqlite3_exec(articlesDB, sql_stmp, NULL, NULL, &errMsg) != SQLITE_OK )
NSLog( @"Fail to create \"IMAGES\" table. Error is: %@", errMsg );

And Here is function for save:

// Save Small Image Data by given main url 
- (void) SaveImagesToSql: (NSData*) imgData :(NSString*) mainUrl
{
NSLog( @"\n*****Save image to SQLite*****\n" );

const char* sqliteQuery = "INSERT INTO IMAGES (URL, IMAGE) VALUES (?, ?)";
sqlite3_stmt* statement;

if( sqlite3_prepare_v2(articlesDB, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )
{
sqlite3_bind_text(statement, 1, [mainUrl UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
}
else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(articlesDB) );

// Finalize and close database.
sqlite3_finalize(statement);
}

And here is function to load images:

// Load images from data base with given image url 
- (NSData*) LoadImagesFromSql: (NSString*) imageLink
{
NSData* data = nil;
NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT IMAGE FROM IMAGES WHERE URL = '%@'", imageLink];
sqlite3_stmt* statement;

if( sqlite3_prepare_v2(articlesDB, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
{
if( sqlite3_step(statement) == SQLITE_ROW )
{
int length = sqlite3_column_bytes(statement, 0);
data = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
}
}

// Finalize and close database.
sqlite3_finalize(statement);

return data;

}

store images into sqlite database

I answered a similair question with this answer: It's better if you use CoreData instead. It will be much easier for you to work with CoreDate instead of SQL. CoreData is pretty much an SQL database in a nice wrapper.

If you use iOS 5 you could easily add images to the database without having to worry about them being BLOBS (Binary Large Object) by checking "Allows External Storage".



Related Topics



Leave a reply



Submit