Home » Android » android – how to convert an image into base64 string

android – how to convert an image into base64 string

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to convert image to base 64 encode to string. from that to send to server with oma_status-icon xml format.

but I am getting unsupported encoding from the server response….

is there any other way to convert image to base64 string??

plz..help…

my code is:

        Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),  R.drawable.image);

        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
        byte [] ba = bao.toByteArray();

         String ba1=Base64.encodeBytes(ba);
How to&Answers:

Please use this code..

Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),  R.drawable.image);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);

Please import

import android.util.Base64;

Answer:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

Answer:

try below code

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte b [] = baos.toByteArray();
String base64String = Base64.encodeToString(b, Base64.DEFAULT);

Dont forget to import android.util.Base64;

Answer:

maybe you can try

String base64Result = Base64.encodeToString(yourByteArray[], Base64.DEFAULT);

Answer:

Method:

private String bitmapToBase64(Bitmap bitmap) {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();

    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

Imports:

import android.util.Base64;
import java.io.ByteArrayOutputStream;