Convert image to base64 String and vice versa

Image to base64 String

To convert image to base64 String use the code given below.
1. Define a new ByteArrayOutputStream.
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
2. Convert image in ImageView to Bitmap.
Bitmap bm = ((android.graphics.drawable.BitmapDrawable) imageview1.getDrawable()).getBitmap();
Or convert image in drawable folder to Bitmap.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
3. Convert bitmap image to byte array and encode it to String.
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Base64 String to image
1. Decode String to Byte array
byte[] imageBytes = Base64.decode(imageString, Base64.DEFAULT);
2. Convert Byte array to Bitmap
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
3. Set the Bitmap as image of ImageView.
imageview1.setImageBitmap(decodedImage);

Here imageString is a base64 String.