项目地址:https://github.com/ZaBlanc/WebImageView
作者对加载图片,以及图片的内存缓存和磁盘缓存做了封装。
代码量不多,但是能够满足一般的加载图片。
先看下项目结构:
我认为通常情况下自己去实现的话,这点需要仔细看下。
/**
*
* @param urlString 对应图片的网络地址
* @return
*/
private String hashURLString(String urlString) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(urlString.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
//fall back to old method
return urlString.replaceAll("[^A-Za-z0-9]", "#");
}
以及这里的文件流操作
@Override
protected Bitmap doInBackground(Void... params) {
// check mem cache first先从内存中查找
Bitmap bitmap = mCache.getBitmapFromMemCache(mURLString);
// check disk cache first然后从磁盘中查找
if (bitmap == null) {
bitmap = mCache.getBitmapFromDiskCache(mContext, mURLString,
mDiskCacheTimeoutInSeconds);
if (bitmap != null) {
//获取到后加入内存中缓存起来
mCache.addBitmapToMemCache(mURLString, bitmap);
}
}
if (bitmap == null) {
InputStream is = null;
FlushedInputStream fis = null;
try {
URL url = new URL(mURLString);
URLConnection conn = url.openConnection();
is = conn.getInputStream();
fis = new FlushedInputStream(is);
bitmap = BitmapFactory.decodeStream(fis);
// cache
if (bitmap != null) {
mCache.addBitmapToCache(mContext, mURLString, bitmap);
}
} catch (Exception ex) {
Log.e(TAG, "Error loading image from URL " + mURLString + ": "
+ ex.toString());
} finally {
try {
is.close();
} catch (Exception ex) {
}
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// complete!完成后回调回去
if (null != mListener) {
if (null == bitmap) {
mListener.onWebImageError();
} else {
mListener.onWebImageLoad(mURLString, bitmap);
}
}
}
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int b = read();
if (b < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
附上源代码:
WebImageCache
/*
Copyright (c) 2011 Rapture In Venice
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), t