9

Is there any way to store image files in firebase using Java api?

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
Kabir
  • 1,419
  • 17
  • 33
  • How do you convert back in to a Bitmap? – Chad Bingham Oct 30 '14 at 23:16
  • 2
    @Binghammer it's simple. byte[] imageAsBytes = Base64.decode(imageFile, Base64.DEFAULT); Bitmap bmp = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length); – Kabir Nov 03 '14 at 02:39
  • 2
    *Firebase just released a new feature called [Firebase Storage](https://firebase.google.com/docs/storage/). This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.* – Frank van Puffelen May 20 '16 at 04:27

1 Answers1

12

Try using this snippet:

Bitmap bmp =  BitmapFactory.decodeResource(getResources(), R.drawable.chicken);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
String imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT); 

and for retrieving

public Bitmap stringToBitMap(String encodedString){
   try {
      byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
      Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
      return bitmap;
   } catch(Exception e) {
      e.getMessage();
      return null;
   }
}
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
sasuri
  • 972
  • 3
  • 11
  • 26
  • 3
    How about displaying image from imageFile string? – Chad Bingham Oct 30 '14 at 23:16
  • 3
    The following should help you with displaying the encoded string as bitmap. byte[] decodedString = Base64.decode(imageFileString, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); imageView.setImageBitmap(bitmap); – ernestkamara Jun 12 '16 at 11:57