how to convert an image into base64 string

2020-02-12 05:20发布

问题:

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);

回答1:

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;


回答2:

// 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);


回答3:

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;



回答4:

maybe you can try

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



回答5:

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;