Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing images to an SQLite DB for iPhone use

Tags:

I've set up a SQLite DB that currently reads and writes NSStrings perfectly. I also want to store an image in the database and recall it later. I've read up a bit on using NSData and encoding the image, but I'm not entirely sure what the syntax is for what I want to do. Any code snippets or examples would be greatly appreciated.

My current process goes like this: UIImagePickerController -> User Chooses Image from Photos -> chosenImage is set to instance of UIImageView -> Now I want to take this image and store it in the DB

I should mention this call will eventually be replaced with a call to a remote server. Not sure if this makes a difference as far as performance goes.

like image 912
Jeff Avatar asked Mar 13 '09 17:03

Jeff


People also ask

Does SQLite work on Iphone?

The database that can be used by apps in iOS (and also used by iOS) is called SQLite, and it's a relational database. It is contained in a C-library that is embedded to the app that is about to use it.

Can you store images in a SQLite database?

Inorder to store images to android SQLite database, you need to convert the image uri to bitmap then to binary characters that is, bytes[] sequence. Then set the table column data type as BLOB data type. After retrieving the images from DB, convert the byte[] data type to bitmap in order to set it to imageview.

Which language is used to read and write data to a SQLite database?

SQLite (/ˌɛsˌkjuːˌɛlˈaɪt/, /ˈsiːkwəˌlaɪt/) is a database engine written in the C programming language.


1 Answers

You'll need to convert the UIImage hosted within your UIImageView into a binary BLOB for storage in SQLite. To do that, you can use the following:

NSData *dataForImage = UIImagePNGRepresentation(cachedImage); sqlite3_bind_blob(yourSavingSQLStatement, 2, [dataForImage bytes], [dataForImage length], SQLITE_TRANSIENT); 

This will generate a PNG representation of your image, store it in an NSData instance, and then bind the bytes from the NSData as a BLOB for the second argument in your SQL query. Use UIImageJPEGRepresentation in the above to store in that format, if you like. You will need to have a BLOB column added to the appropriate table in your SQLite database.

To retrieve this image, you can use the following:

NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(yourLoadingSQLStatement, 2) length: sqlite3_column_bytes(yourLoadingSQLStatement, 2)];        self.cachedImage = [UIImage imageWithData:dataForCachedImage]; [dataForCachedImage release]; 
like image 174
Brad Larson Avatar answered Sep 21 '22 12:09

Brad Larson