简体   繁体   English

有多少种方法可以将位图转换为字符串,反之亦然?

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

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 Base64 format for encoding and decoding, it takes little bit more memory. 现在我使用Base64格式进行编码和解码,它需要更多的内存。 is there any other possibilities to do the same thing in different ways which takes less memory cosumptions. 有没有其他可能以不同的方式做同样的事情,这需要更少的内存消耗。 Now i am using this code. 现在我正在使用此代码。

Resources r = ShowFullImage.this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.col);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
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 以下是将字符串转换为位图的相反过程,但字符串应为Base64编码

/**
 * @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. 您可以使用byteArray发送图像或其他数据。 there is no encoding and decoding require. 没有编码和解码需要。 and you have to use multipart body to send data to server.. 你必须使用multipart body将数据发送到服务器..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM