Reputation: 41
I have been trying to store image form android sdcard to the sqlite database. And it worked fine. The image is getting stored into the database as blob. This is the rough code I have been using for that.
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(bitmap);
int size = bitmap.getWidth() * bitmap.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();}
byte[] x = out.toByteArray();
In the database side, the code is like this
ContentValues values = new ContentValues();
byte[] bytes = null;
bytes = img_bytes.getBytes();
values.put("IMAGE", bytes);
And for displaying I have used the code as below.
ImageView image = new ImageView(this);
byte[] img_bytes = result.get("IMAGE").getBytes();
Bitmap bMap = BitmapFactory.decodeByteArray(img_bytes, 0, img_bytes.length);
image.setImageBitmap(bMap);
When I printed the string value of the byate array, it was getting like [B@44da2db0. But the byte array is not getting displayed into image.
Somebody please help me with this. Thanks
Upvotes: 0
Views: 6282
Reputation: 41
I have found a solution. Thanks to all.
I have used base64 encoding method. ie; For displaying the image, I have been using a hash map to get the result first of all from the database table. So before saving into the map, I have encoded the bytes to string using base 64 method. Then On the Activity side for displaying the image, I have decoded back the string using base 64 again and then converted to bytes and the image got displayed.
Upvotes: 3