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

后端 未结 3 1833
死守一世寂寞
死守一世寂寞 2020-11-30 04:11

In my application i want to send bitmap image to the server in the form of string, i want to know how many ways are available to convert a bitmap to string. now i am using B

相关标签:
3条回答
  • 2020-11-30 04:12
    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;
       }
    }
    
    0 讨论(0)
  • 2020-11-30 04:30

    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..

    0 讨论(0)
  • 2020-11-30 04:39

    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;
    }
    
    0 讨论(0)
提交回复
热议问题