从服务器获取图像并在 Imageview 中显示的 Android 代码

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 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)