Android+Java get image from URL on server and pass

2019-06-02 19:27发布

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,

3条回答
男人必须洒脱
2楼-- · 2019-06-02 19:47

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;
   }
}
查看更多
放荡不羁爱自由
3楼-- · 2019-06-02 19:56

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!

查看更多
姐就是有狂的资本
4楼-- · 2019-06-02 20:06

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

查看更多
登录 后发表回答