0

I'm trying to retrieve a Base64 encoded image from Firebase and show it on an App developed in Android Studio. The code is putting something on the ImageView element, but I think that is just a white image, because the background of the ImageView element just disappears. Can someone help?

public class MainActivity extends AppCompatActivity {

    private Button setting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView image = (ImageView) findViewById(R.id.CamaraImage);
        FirebaseDatabase.getInstance().getReference().child("photos").child("realtime").child("-MbB__vRH7wrFXqL_8UO").child("photo").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String imagestr = dataSnapshot.getValue(String.class);
                String imageclean = imagestr.replace("data:image/jpeg;base64,", "");
                //64Base to BitMap Conversion
                byte[] decodedString = Base64.decode(imageclean, Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                image.setImageBitmap(decodedByte);
                //Toast.makeText(MainActivity.this, imageclean, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Bert
  • 25
  • 3

1 Answers1

0

As per this User answer the correct string format is

"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."

And to decode that particular string to image you can use the following code

String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);

InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
  • Thank you for your answer, but it does the same... I dont know why but it only puts a white image instead of the photo that i want! Maybe something on the layouts or image view? – Bert Jun 04 '21 at 10:22