Store images/files in database


SDK Version: 
M3

Hoever the practice is to store them normally and save the access route (Uri), sometimes it can be handy to store files/images completely in database.
In sqlite database there are only a few data types, so its easy to choose: files can be stored in a text as a ByteArray.

Lets see a sample code, where we download an image from the Internet then store it in the local database:

  1. //where we want to download it from
  2. URL url = new URL(IMAGE_URL);  //http://example.com/image.jpg
  3. //open the connection
  4. URLConnection ucon = url.openConnection();
  5. //buffer the download
  6. InputStream is = ucon.getInputStream();
  7. ByteArrayBuffer baf = new ByteArrayBuffer(128);
  8. //get the bytes one by one
  9. int current = 0;
  10. while ((current = bis.read()) != -1) {
  11.         baf.append((byte) current);
  12. }
  13.  
  14. //store the data as a ByteArray
  15. //db is a SQLiteDatabase object
  16. ContentValues dataToInsert = new ContentValues();                          
  17. dataToInsert.put(TABLE_FIELD,baf.toByteArray());
  18. db.insert(TABLE_NAME, null, dataToInsert);

And this is how you get the data back and convert it into a Bitmap:

  1. //select the data
  2. Cursor cursor = db.query(TABLE_STATIONLIST, new String[] {TABLE_FIELD},
  3.                                                 null, null, null, null, null);
  4. //get it as a ByteArray
  5. byte[] imageByteArray=cursor.getBlob(1);
  6. //the cursor is not needed anymore
  7. cursor.close();
  8.  
  9. //convert it back to an image
  10. ByteArrayInputStream imageStream = new ByteArrayInputStream(mybyte);
  11. Bitmap theImage = BitmapFactory.decodeStream(imageStream));

Storing a lot or big images in database is not recommended, but you can keep this solution in mind, there can be cases where this method can help you.

As the example shows in general it is possible to store anything in a database easily if you can convert it into a byte array.

If you're looking for the latest tips for your android phone, then check out the Dialaphone which always publishes the latest news from the mobile phone world. Click here for more information and to read their latest news, reviews and articles.