imageview 直接加载图片流
第一步:new一个线程直接获取接口返回的图片流stream,如果项目使用的网络请求框架能直接获取inputstream,那就不需要自己写线程。
/**
* 获取网络图片资源
*
* @param urlString
* @return
*/
public void getHttpBitmap(final String urlString) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
Bitmap bitmap = null;
final InputStream is = connection.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
} else {
try {
byte[] data = readStream(is);
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (Exception e) {
e.printStackTrace();
}
is.close();
}
// // 下面对获取到的输入流进行读取
// BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// StringBuilder response = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// response.append(line);
// }
Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到Message中
message.obj = bitmap;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
第二步:
如果直接使用
BitmapFactory.decodeStream(inputStream)
,这个时候得到的是null。
原因:应该是decodeStream的时候流已经关闭。因为我是把inputstream放在message中,传递到handle中,再解析流。
参考:http://blog.csdn.net/maxwell_nc/article/details/49081105
/*
* 得到图片字节流 数组大小
* */
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
第三步:
在handle中接收处理
public final static int SHOW_RESPONSE = 110;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
//然后使用方法decodeByteArray()方法解析编码,生成Bitmap对象。
mIvCaptcha.setImageBitmap((Bitmap) msg.obj);
}
}
};