Android代码,用于从服务器获取图像并在Imageview中显示 [英] Android code to fetch Image from server and display it in Imageview
问题描述
您好我知道如何从jsonobject获取字符串,但我的问题是如何从Rest api获取图像并显示它。图像存储为jsonobject中的profile_image
我的代码:
试试{
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)){
//这里必须做什么
}
有几种可能的情况:
案例1. 图像是Base64,然后您需要对其进行解码并使用BitmapFactory方法:
byte [] decodingString = Base64.decode(encodedImage,Base64.DEFAULT);
Bitmap decodingByte = BitmapFactory.decodeByteArray(decodingString,0,encodedString.length);
案例2. Json包含图像链接。只需加载链接,当您收到Stream对象时,将其传递给BitmapFactory。这样的事情:
InputStream instream = httpEntity.getContent();
bmp = BitmapFactory.decodeStream(instream);
以上示例使用HttpClient类,搜索api文档,了解如何从您使用过的网络库中获取InputStream。 / p>
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
My code:
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
}
There are several possible cases:
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);
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);
Above example uses HttpClient class, search api docs on how to get InputStream from your used network library.
这篇关于Android代码,用于从服务器获取图像并在Imageview中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!