当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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,

网友答案:

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!

网友答案:

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

网友答案:

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;
   }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: