Android code to fetch Image from server and display it in Imageview(从服务器获取图像并在 Imageview 中显示的 Android 代码)

本文介绍了从服务器获取图像并在 Imageview 中显示的 Android 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我知道如何从 jsonobject 获取字符串,但我的问题是如何从 Rest api 获取图像并显示它.图片作为profile_image存储在jsonobject中

Hi I know how to fetch an string from jsonobject, but my question is how to fetch an image from Rest api and display it. The image is stored as profile_image in jsonobject

我的代码:

 try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject object = jsonObject.getJSONObject("user");
                    String attr1 = object.getString("username");
                    data = "" + attr1;
                    textView15.setText(data);
                    if (object.has("profession")) {
                        String attr2 = object.getString("profession");
                        data2 = "" + attr2;
                        textView16.setText(data2);
                    }
                    if(object.has("company")){
                        String attr3 = object.getString("company");
                        data3 = "" + attr3;
                     textView38.setText(data3);
                    }

                    if(object.has("profile_image")) {
                        //what has to be done here
                    }

推荐答案

有几种可能的情况:

案例1.图片是Base64,需要解码使用BitmapFactory方法:

Case 1. Image is Base64, then you need to decode it and use BitmapFactory method:

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

案例 2. Json 包含图片链接.只需加载链接,当您收到 Stream 对象时,将其传递给 BitmapFactory.像这样的:

Case 2. Json contains link to image. Simply load the link, and when you receive Stream object, pass it to BitmapFactory. Something like this:

InputStream instream = httpEntity.getContent();
bmp = BitmapFactory.decodeStream(instream);

以上示例使用 HttpClient 类,搜索 api 文档了解如何从您使用的网络库中获取 InputStream.

Above example uses HttpClient class, search api docs on how to get InputStream from your used network library.

这篇关于从服务器获取图像并在 Imageview 中显示的 Android 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!