如何在Android中将图像转换为base64字符串?

Gow*_* Bk 5 java android android-studio

Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.image);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    final String encodedImage = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)

这是我的代码。它将图像上传到服务器。但是,我所看到的只是一个盒子。我要去哪里错了?

Jos*_*eph 2

确保在最后(即服务器端)转换回位图

1、将图像视图转换为位图。

 imageView.buildDrawingCache();
 Bitmap bmap = imageView.getDrawingCache();
Run Code Online (Sandbox Code Playgroud)

2、将bitmap转换为base64 String并传递给服务器

public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  bitmap.compress(CompressFormat.JPEG, 70, stream);
  byte[] byteFormat = stream.toByteArray();
  // get the base 64 string
  String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
  return imgString;
}
Run Code Online (Sandbox Code Playgroud)

3、在服务器端将base64转换为位图。(这是java代码,用你的服务器端语言来做)

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Run Code Online (Sandbox Code Playgroud)

设置此位图以显示图像