![](/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.