How many ways to convert bitmap to string and vice-versa?

冷暖自知 提交于 2019-11-27 07:58:36
sachin10
public String BitMapToString(Bitmap bitmap){
     ByteArrayOutputStream baos=new  ByteArrayOutputStream();
     bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
     byte [] b=baos.toByteArray();
     String temp=Base64.encodeToString(b, Base64.DEFAULT);
     return temp;
}

Here is the reverse procedure for converting string to bitmap but string should Base64 encoding

/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public Bitmap StringToBitMap(String encodedString){
   try {
      byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
      Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
      return bitmap;
   } catch(Exception e) {
      e.getMessage();
      return null;
   }
}

Yes, You can do it by implenment this code :

String to Bitmap :

 public Bitmap StringToBitMap(String encodedString) {
    try {
        byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
                encodeByte.length);
        return bitmap;
    } catch (Exception e) {
        e.getMessage();
        return null;
    }
}

Bitmap to String :

public String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

you can use byteArray to send images or other data. there is no encoding and decoding require. and you have to use multipart body to send data to server..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!