dancingbush
dancingbush

Reputation: 2281

Best method to save & retrieve images to database

Looking for advice on above. Looking to create a SQLlite DB where each row of data is mainly strings but I also want to save an image taken from the phone.

Is it advisable or possible to save the encoded base 64 string of a bitmap image and convert it back to image when the row of data is called?

I also read somewhere that there is a blob column type that can save image binary data.

Thanks in advance!

Cheers

Upvotes: 4

Views: 6216

Answers (1)

Submersed
Submersed

Reputation: 8870

Yes, it's definitely possible to do, but you could also use Blobs as well (see this post How to store and retrieve a byte array (image data) to and from a SQLite database?). If you want to store the images as Base64 strings, though, it's pretty easy to do, just use the Apache library to encode the raw image bytes[] to a Base64 String.

Here's the reference: Apache Base 64

First you'll want to encode the image bytes[] using public static String encodeBase64String(byte[] binaryData).

Then, you can store the Base64 String in your database.

When you go to retrieve the image, just use public static byte[] decodeBase64(String base64Data) to convert the String back to bytes[], and use the BitmapFactory to get the Bitmap.

Edit:

Played around with this for a bit, and for some reason after adding the core commons-codec-1.9.jar, I get a java.lang.NoSuchMethodError. In case this problem isn't specific to my build, it's the same as:

String base64string = new String(Base64.encodeBase64(drawable), "UTF-8");

Upvotes: 4

Related Questions