Android + Java从服务器上的URL获取图像并作为字符串传递给客户端:Base64解码和编码无法正常工作

在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)); 

结果:图像未显示,不是服务器上或客户端上的错误/exception。

这里有什么问题?

编辑:在Android上我使用类android.util.Base64

谢谢,

如上所述,我们假设base64Content是从您的Web服务/服务器端应用程序响应的base64字符串,您可以参考以下示例代码:

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

此外,如果您的服务器通过gzipdeflate压缩响应数据,您的客户端应用程序必须首先解压缩数据。

希望这可以帮助!

使用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; } }