今天做项目,需要从网络获取图片,然后加载到Listview里面。
这边需要分为两步。
第一步:从网络获取图片
public InputStream getImageViewInputStream(String userID)
throws IOException {
InputStream inputStream = null;
//头像图片的网络地址
String URL_PATH = "http://192.168.2.37/ftpweb/peo/" + userID + "_2.jpg";
URL url = new URL(URL_PATH); // 服务器地址
if (url != null) {
// 打开连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(3000);// 设置网络连接超时的时间为3秒
httpURLConnection.setRequestMethod("GET"); // 设置请求方法为GET
httpURLConnection.setDoInput(true); // 打开输入流
int responseCode = httpURLConnection.getResponseCode(); // 获取服务器响应值
if (responseCode == HttpURLConnection.HTTP_OK) { // 正常连接
inputStream = httpURLConnection.getInputStream(); // 获取输入流
}
}
return inputStream;
}
第二步:获取的输入流处理为drawable格式
因为我们返回的是一个输入流,所以获取到图片之后需要进行转化。这边我把输入流先转化成了bitmap格式,再从bitmap格式转化drawable格式,最后把drawable传入map中,添加到list里面。
这边是把输入流转化为bitmap,再从bitmap转化为drawable,bd.nutate()的方法可以转化为drawable。
Bitmap bitmap = null;
BitmapDrawable bd =null;
try {
InputStream inputStream = getImageViewInputStream(userID);
bitmap = BitmapFactory.decodeStream(inputStream);
bd = new BitmapDrawable(bitmap);
} catch (IOException e) {
}
map.put("head", bd.mutate());