![](/img/trans.png)
[英]Java: How to convert a String of Binary values to a Float and vice-versa?
[英]How many ways to convert bitmap to string and vice-versa?
在我的应用程序中,我想以字符串的形式将位图图像发送到服务器,我想知道有多少种方法可以将位图转换为字符串。 现在我使用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);
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;
}
}
是的,您可以通过实现此代码来实现:
字符串到位图:
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;
}
您可以使用byteArray发送图像或其他数据。 没有编码和解码需要。 你必须使用multipart body将数据发送到服务器..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.