Android+Java get image from URL on server and pass as string to client: Base64 decode and encode not working

喜欢而已 提交于 2019-12-23 02:30:10

问题


In Java server I fetch image from external service URL like:

InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));

Then on Android I parse it like:

byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

Result: Image not displayed, ain't errors/exceptions neither on server nor on client.

What is the problem here?

EDIT: On android I use class android.util.Base64

Thanks,


回答1:


As commented, let's assume base64Content is the base64 string responsed from your web service/server-side app, you can refer to the following sample code:

String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 

Moreover, if your server compressed reponse data either by gzip or deflate, your client app must decompress the data first.

Hope this helps!




回答2:


Use Picasso library to load image:

You just need to add 1 line of code to show the image on ImageView

//Loading image from below url into imageView

Picasso.with(this)
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

You can learn more from here




回答3:


use this to convert to 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;
   }
}


来源:https://stackoverflow.com/questions/33032924/androidjava-get-image-from-url-on-server-and-pass-as-string-to-client-base64-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!