[英]Android+Java get image from URL on server and pass as string to client: Base64 decode and encode not working
在 Java 服務器中,我從外部服務 URL 獲取圖像,例如:
InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
然后在Android上我解析它:
byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
結果:圖像未顯示,在服務器和客戶端上都沒有錯誤/異常。
這里有什么問題?
編輯:在 android 上我使用類android.util.Base64
謝謝,
使用 Picasso 庫加載圖像:
您只需要添加 1 行代碼即可在 ImageView 上顯示圖像
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
你可以從這里了解更多
使用它來轉換為 base 64
public static String uploadPic(Bitmap bm) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = ""+ Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
check if image is uploaded then using volley String request object download the string response using this code convert it back.
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;
}
}
正如所評論的,讓我們假設base64Content
是從您的 Web 服務/服務器端應用程序響應的 base64 字符串,您可以參考以下示例代碼:
String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
此外,如果您的服務器通過gzip或deflate壓縮響應數據,則您的客戶端應用程序必須先解壓縮數據。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.