最近有个需求,从网络下载图片,但不能使用imageloader,因为iimageloader使用缓存机制,同一路径下的图片如果跟换怎不会刷新替换。所以必须自己下载解析。但遇到OOM的问题,如果用BitmapFactory.decodeStream 则会返回null,所以我采用的办法是先将图片下载下来,再计算图片宽高,最后绑定图片后将图片删除的办法。话不多说,先上代码
//path为图片的网络路径
private Bitmap getHttpBitmap(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
//获取图片路径
String[] names = path.split("/");
String name = names[names.length-1];
//保存图片到本地
FileOutputStream outStream = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/"+ name));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
//获取图片宽高
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"+ name , opts);
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
Log.i("imageWidth", String.valueOf(imageWidth));
Log.i("imageHeight", String.valueOf(imageHeight));
//计算缩放比例,此处100为默认值,也可以获取控件宽高进行计算
int widthscale = imageWidth / 100;
int heightscale = imageHeight / 100;
int scale = widthscale > heightscale ? widthscale
: heightscale;
Log.i("scale", String.valueOf(scale));
//开始真正获取图片,进行压缩后的图片
opts.inJustDecodeBounds = false;
opts.inSampleSize = scale;
localerweima =Environment.getExternalStorageDirectory() + "/"+ name;
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/"+ name , opts);
Log.i("bitmap1", String.valueOf(bitmap));
is.close();
Message msg = Message.obtain();
msg.what = 1;
msg.obj = bitmap;
handler.sendMessage(msg);
return bitmap;
}
return null;
} catch (Exception e) {
Log.i("e.toString();", e.toString());
return null;
}
}
//这是handler绑定图片并删除文件的操作
Message msg = new Message();
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: // 二维码
Bitmap bm = (Bitmap) msg.obj;
tv_erweima.setImageBitmap(bm);
new File(localerweima).delete(); //每次绑定完成后删除本地文件
break;
default:
break;
}
};
};