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

时间:2016-03-16 08:59:56

标签: 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);

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

2 个答案:

答案 0 :(得分:2)

确保在结束时转换回位图,即服务器端

1,将您的imageview转换为位图。

 imageView.buildDrawingCache();
 Bitmap bmap = imageView.getDrawingCache();

2,将位图转换为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;
}

3,在服务器端将base64转换为位图。 (这是java代码,用您的服务器端语言执行)

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

将此位图设置为显示图像

答案 1 :(得分:0)

将图片转换为位图。

 File imagefile = new File(Environment.getExternalStorageDirectory(),"/image/test.jpg" );
    FileInputStream fis = null;
                try {
                    fis = new FileInputStream(imagefile);
                    } catch (FileNotFoundException e) {
                        logger.error(Log.getStackTraceString(e));
                    e.printStackTrace();
                }

  Bitmap bm = BitmapFactory.decodeStream(fis);

位图到字节[]

 ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                bm.compress(Bitmap.CompressFormat.PNG, 10 , baos);    
                byte[] img = baos.toByteArray();

字节[]到字符串:

String s= Base64.encodeToString(img , Base64.DEFAULT)