如何在Android中从url获取字节图像

3 java android json android-studio

我是 android 新手。图像以Base64格式存储在服务器中。那么我如何将它从服务器获取到我的项目并使用 Json 对象设置到我的 ImageView 。请帮我

任何帮助将不胜感激

Jas*_*Jas 5

尝试这个:

首先将 Url 转换为 byte[]:

byte[] bitmapdata = getByteArrayImage(url);
Run Code Online (Sandbox Code Playgroud)

方法:

private byte[] getByteArrayImage(String url){
         try {
                 URL imageUrl = new URL(url);
                 URLConnection ucon = imageUrl.openConnection();

                 InputStream is = ucon.getInputStream();
                 BufferedInputStream bis = new BufferedInputStream(is);

                 ByteArrayBuffer baf = new ByteArrayBuffer(500);
                 int current = 0;
                 while ((current = bis.read()) != -1) {
                         baf.append((byte) current);
                 }

                 return baf.toByteArray();
         } catch (Exception e) {
                 Log.d("ImageManager", "Error: " + e.toString());
         }
         return null;
    }
Run Code Online (Sandbox Code Playgroud)

现在将 byte[] 转换为位图

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
Run Code Online (Sandbox Code Playgroud)

并将位图设置为 ImageView:

img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
Run Code Online (Sandbox Code Playgroud)