在开发中,遇到很多大量图片呈现给用户,那么我们怎么又快又高效的显示给用户呢?
在这里结合前人写的文章和自己的一些改动。
一般我们写的过程中是这么处理的:先去缓存(WeakHashMap<String, Bitmap>来存储图片)中提取,这样速度快又节约流量,缓存中没有再选择本地有图片没有,如果两者都没有则只有从网络去获取。
我们先分开讲解
方法一:网络下载
方法二:从本地文件加载
方法三:从缓存中读取
先来说方法一:
加载很多图片的时候,我们经常用多线程在后台下载,在handler中将图片呈现在界面。
直接上代码
//网络获取图片
protected Bitmap getNetBitmapByURL(String urlString) {
URL url = null;
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
Bitmap bmp = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(10000);
inputStream = urlConnection.getInputStream();
byte[] bt = getBytesFromStream(inputStream);
bmp = BitmapFactory.decodeByteArray(bt, 0, bt.length);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != urlConnection) {
urlConnection.disconnect();
urlConnection = null;
}
}
return bmp;
}
// 数据流
private byte[] getBytesFromStream(InputStream inputStream) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while (len != -1) {
try {
len = inputStream.read(b);
} catch (IOException e) {
e.printStackTrace();
}
if (len != -1) {
baos.write(b, 0, len);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return baos.toByteArray();
}
这个地方获取了Bitmap 用handler呈现就很好搞定
再来说方法二本地获取:
直接根据图片路径获取Bitmap
private boolean cacheBmpToMemory(File file) {
boolean sucessed = true;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
sucessed = false;
}
byte[] bs = getBytesFromStream(inputStream);
Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
if (bitmap == null) {
return null;
}
return bitmap;
}
private byte[] getBytesFromStream(InputStream inputStream) {
boolean b2 = true;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while (len != -1 && b2) {
try {
len = inputStream.read(b);
if (len != -1) {
baos.write(b, 0, len);
}
} catch (IOException e) {
b2 = false;
try {
inputStream.close();
} catch (IOException e1) {
}
}
}
if (inputStream != null) {
try {
inputStream.close()