How to convert an Image to Base64 String

Usually we don't need to have an Image converted into the Base64 String coded. But when we work with Databasea especially with SQL and in my case (Firebase), we have to convert all our images into Base64 String in order to save our images inside databases.

To convert an Image into Base64 String inside Java



       private String ImageToString(int draw){
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               Bitmap bitmap = BitmapFactory.decodeResource(getResources(), draw);
               bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
               byte[] imageBytes = baos.toByteArray();
               String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
               return imageString;
        }

Here is the way you can use this method. All need to do is this:

String StringImage = ImageToString(R.drawable.ImageNameHere);

There you go, now you can easily pass this ImageString inside any database or Storage.

To convert a Base64 String into Image inside JAVA



       private Bitmap ImageDecoder(String draw){
           byte[] imageBytes = Base64.decode(draw, Base64.DEFAULT);
           Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
           return decodedImage;
      }

By using the above code, all you need to do is:

Bitmap img = ImageDecoder(StringOFImage);

now you can use your image anywhere you like.









GIVE FEEDBACK ()