Android Convert Bitmap to Base64 String: Easy Solution
If you're looking for an easy solution to convert a Bitmap to a Base64 String in Android, you're in the right place. The process is simple and can be done in just a few lines of code.
First, you need to convert the Bitmap to a byte array using the Bitmap.compress() method. This method takes a Bitmap.CompressFormat and a quality value as parameters. The CompressFormat can be either JPEG, PNG or WEBP, and the quality value is an integer between 0 and 100.
Once you have the byte array, you can use the android.util.Base64 class to encode it into a Base64 String. The Base64 class provides two methods for encoding: encodeToString() and encode(). The former returns a String, while the latter returns a byte array.
Here's an example code snippet that converts a Bitmap to a Base64 String:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String base64String = Base64.encodeToString(imageBytes, Base64.DEFAULT);
In this example, we first decode a Bitmap from a resource using BitmapFactory.decodeResource(). Then we compress the Bitmap to a JPEG byte array with a quality of 100. Next, we convert the byte array to a Base64 String using Base64.encodeToString(). Finally, the resulting String is stored in the base64String variable.
And that's it! With just a few lines of code, you can easily convert a Bitmap to a Base64 String in Android.
Leave a Reply
Related posts