如何将位图转换为字符串,以及反向转换的方法有哪些?

42
在我的应用程序中,我想将位图图像以字符串形式发送到服务器,我想知道有多少种方法可用于将位图转换为字符串。现在,我正在使用Base64格式进行编码和解码,它需要更多的内存。是否有其他可能的方法可以以不同的方式执行相同的操作,从而减少内存消耗。 现在我正在使用这段代码。
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);
3个回答

92
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;
}

这里是将字符串转换为位图的反向过程,但是字符串应该进行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;
   }
}

已经我在使用 Base64 格式,我正在寻找另一种格式。 - RajaReddy PolamReddy
我的代码和你的代码有什么区别?我正在寻找除了使用Base64之外的不同转换方式。 - RajaReddy PolamReddy
1
StringToBitMap返回null。请帮帮我。 - Akshay kumar
尝试在空对象引用上调用虚拟方法'byte[] java.lang.String.getBytes()'。这是我从StringToBitmap得到的。 - Michael

4
是的,您可以通过实现以下代码来完成:
将字符串转换为位图:
 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;
    }
}

位图转字符串:

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

2

你可以使用byteArray发送图片或其他数据,无需进行编码和解码。你需要使用multipart body将数据发送到服务器。


如果您能分享如何使用多部分正文上传图像的答案,那将非常令人赞赏和有用(可以包括Android和服务器代码块)。 - dev1234

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接