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 = android.util.Base64.encodeToString(imageBytes, android.util.Base64.DEFAULT);

Base64 String to image

1. Decode String to Byte array
byte[] imageBytes = android.util.Base64.decode(imageString, android.util.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.

Komentar

Cara pembuatan Apps paling Populer

Create Stopwatch App in Android using Sketchware

How to enable download in webview in Sketchware apps?

TextInputLayout in Sketchware

Create Stopwatch App in Android using Sketchware

How to integrate Admob Ads in Sketchware project using AIDE?

How to find and​ highlight a word in a text field in Sketchware?

Code for implementing Notifications in Sketchware

A Flash Light App in Sketchware

Create a Stopwatch App using Chronometer in Sketchware

Create app to save all passwords, protected using voice key