Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert an image into base64 string in android?

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

This is my code. It uploads the image onto the server. However, All I can see is a box. Where am I going wrong?

like image 283
Gowtham Bk Avatar asked Oct 31 '22 07:10

Gowtham Bk


1 Answers

Make sure you convert back to bitmap at the End, ie Server side

1, convert your imageview to bitmap.

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

2, convert bitmap to base64 String and pass to server

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, At server side convert base64 to bitmap. (this is java code, do it in your server side language)

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

set this bitmap to display image

like image 158
Joseph Joseph Avatar answered Nov 09 '22 09:11

Joseph Joseph