将网络图片 转化成bitmap
2018-09-10 本文已影响3人
zhengLH
【1】解析图片 在 子线程, 解析完成 使用Handler 通知到主线程。
/**
* 根据 图片URL 转换成 Bitmap
* @param url
* @return
*/
public static Bitmap returnBitMap(final String url, final android.os.Handler handler){
new Thread(new Runnable() {
@Override
public void run() {
URL imageurl = null;
try {
imageurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
Message message = handler.obtainMessage();
message.obj = bitmap;
message.arg1 = 1;
handler.sendMessage(message);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return bitmap;
}
【2】 使用
ImageUtil.returnBitMap(picUrl, new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// todo 具体逻辑
Bitmap mBitmap = (Bitmap) msg.obj;
int width = mBitmap.getWidth();
int height = mBitmap.getHeight();
final float picScale = (float) width/height; // 宽高比
}
});