项目地址:https://github.com/ZaBlanc/WebImageView

作者对载入图片,以及图片的内存缓存和磁盘缓存做了封装。

代码量不多。可是可以满足一般的载入图片。

先看下项目结构:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveHhtMjgyODI4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

我觉得通常情况下自己去实现的话,这点须要细致看下。

/**
*
* @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"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/ package com.raptureinvenice.webimageview.cache; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log; /**
* 处理图片缓存的类
*
*/
public class WebImageCache {
private final static String TAG = WebImageCache.class.getSimpleName(); // cache rules
/**
* 是否同意内存缓存
*/
private static boolean mIsMemoryCachingEnabled = true;
/**
* 是否同意磁盘缓存
*/
private static boolean mIsDiskCachingEnabled = true;
/**
* 缺省的默认超时显示时间
*/
private static int mDefaultDiskCacheTimeoutInSeconds = 60 * 60 * 24; // one day default /**
* 缓存 软饮用?说好的弱引用呢??
*/
private Map<String, SoftReference<Bitmap>> mMemCache; public WebImageCache() {
mMemCache = new HashMap<String, SoftReference<Bitmap>>();
} // ----------setter and getter
public static void setMemoryCachingEnabled(boolean enabled) {
mIsMemoryCachingEnabled = enabled;
Log.v(TAG, "Memory cache " + (enabled ? "enabled" : "disabled") + ".");
} public static void setDiskCachingEnabled(boolean enabled) {
mIsDiskCachingEnabled = enabled;
Log.v(TAG, "Disk cache " + (enabled ? "enabled" : "disabled") + ".");
} public static void setDiskCachingDefaultCacheTimeout(int seconds) {
mDefaultDiskCacheTimeoutInSeconds = seconds;
Log.v(TAG, "Disk cache timeout set to " + seconds + " seconds.");
} /**
* 从缓存中取出图片
* @param urlString 相应图片的URL,在cache中是键
* @return
*/
public Bitmap getBitmapFromMemCache(String urlString) {
if (mIsMemoryCachingEnabled) {
//同步缓存
synchronized (mMemCache) {
SoftReference<Bitmap> bitmapRef = mMemCache.get(urlString); if (bitmapRef != null) {
Bitmap bitmap = bitmapRef.get(); if (bitmap == null) {
//键相应的Bitmap为空,则T掉。去掉无效值
mMemCache.remove(urlString);
Log.v(TAG, "Expiring memory cache for URL " + urlString + ".");
} else {
Log.v(TAG, "Retrieved " + urlString + " from memory cache.");
return bitmap;
}
}
}
} return null;
} /**
* 从磁盘中获取缓存图片
* @param context
* @param urlString
* @param diskCacheTimeoutInSeconds
* @return
*/
public Bitmap getBitmapFromDiskCache(Context context, String urlString, int diskCacheTimeoutInSeconds) {
if (mIsDiskCachingEnabled) {
Bitmap bitmap = null;
File path = context.getCacheDir();
InputStream is = null;
String hashedURLString = hashURLString(urlString); // correct timeout保证正确的超时设置
if (diskCacheTimeoutInSeconds < 0) {
diskCacheTimeoutInSeconds = mDefaultDiskCacheTimeoutInSeconds;
} File file = new File(path, hashedURLString); if (file.exists() && file.canRead()) {
// check for timeout
if ((file.lastModified() + (diskCacheTimeoutInSeconds * 1000L)) < new Date().getTime()) {
Log.v(TAG, "Expiring disk cache (TO: " + diskCacheTimeoutInSeconds + "s) for URL " + urlString); // expire
file.delete();
} else {
try {
is = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(is);
Log.v(TAG, "Retrieved " + urlString + " from disk cache (TO: " + diskCacheTimeoutInSeconds + "s).");
} catch (Exception ex) {
Log.e(TAG, "Could not retrieve " + urlString + " from disk cache: " + ex.toString());
} finally {
try {
is.close();
} catch (Exception ex) {}
}
}
} return bitmap;
} return null;
} /**
* 将图片增加缓存中
* @param urlString 相应的http网络地址
* @param bitmap 相应的Bitmap对象
*/
public void addBitmapToMemCache(String urlString, Bitmap bitmap) {
if (mIsMemoryCachingEnabled) {
synchronized (mMemCache) {
mMemCache.put(urlString, new SoftReference<Bitmap>(bitmap));
}
}
} /**
* 将图片增加磁盘缓存中
* @param context
* @param urlString
* @param bitmap
*/
public void addBitmapToCache(Context context, String urlString, Bitmap bitmap) {
// mem cache
addBitmapToMemCache(urlString, bitmap); // disk cache
// TODO: manual cache cleanup
if (mIsDiskCachingEnabled) {
File path = context.getCacheDir();
OutputStream os = null;
String hashedURLString = hashURLString(urlString); try {
// NOWORKY File tmpFile = File.createTempFile("wic.", null);
File file = new File(path, hashedURLString);
os = new FileOutputStream(file.getAbsolutePath()); //对图片进行压缩处理
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close(); // NOWORKY tmpFile.renameTo(file);
} catch (Exception ex) {
Log.e(TAG, "Could not store " + urlString + " to disk cache: " + ex.toString());
} finally {
try {
os.close();
} catch (Exception ex) {}
}
}
} /**
*
* @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]", "#");
}
}

WebImageManagerRetriever

/*
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"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/ package com.raptureinvenice.webimageview.download; import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log; import com.raptureinvenice.webimageview.cache.WebImageCache; /**
*
* 异步获取图片
*/
public class WebImageManagerRetriever extends AsyncTask<Void, Void, Bitmap> {
private final static String TAG = WebImageManagerRetriever.class
.getSimpleName(); // cache
private static WebImageCache mCache; // what we're looking for
private Context mContext;
private String mURLString;
private int mDiskCacheTimeoutInSeconds;
/**
* 回调
*/
private OnWebImageLoadListener mListener; static {
mCache = new WebImageCache();
} public WebImageManagerRetriever(Context context, String urlString,
int diskCacheTimeoutInSeconds, OnWebImageLoadListener listener) {
mContext = context;
mURLString = urlString;
mDiskCacheTimeoutInSeconds = diskCacheTimeoutInSeconds;
mListener = listener;
} @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;
}
} public interface OnWebImageLoadListener {
public void onWebImageLoad(String url, Bitmap bitmap); public void onWebImageError();
}
}

WebImageManager

/*
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"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/ package com.raptureinvenice.webimageview.download; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; import android.content.Context;
import android.graphics.Bitmap; import com.raptureinvenice.webimageview.download.WebImageManagerRetriever.OnWebImageLoadListener;
import com.raptureinvenice.webimageview.image.WebImageView; public class WebImageManager implements OnWebImageLoadListener {
private static WebImageManager mInstance = null; // TODO: pool retrievers // views waiting for an image to load in
private Map<String, WebImageManagerRetriever> mRetrievers;
private Map<WebImageManagerRetriever, Set<WebImageView>> mRetrieverWaiters;
private Set<WebImageView> mWaiters; public static WebImageManager getInstance() {
if (mInstance == null) {
mInstance = new WebImageManager();
} return mInstance;
} private WebImageManager() {
mRetrievers = new HashMap<String, WebImageManagerRetriever>();
mRetrieverWaiters = new HashMap<WebImageManagerRetriever, Set<WebImageView>>();
mWaiters = new HashSet<WebImageView>();
} /**
* 处理多个同一时候载入图片
* @param context
* @param urlString
* @param view
* @param diskCacheTimeoutInSeconds
*/
public void downloadURL(Context context, String urlString, final WebImageView view, int diskCacheTimeoutInSeconds) {
WebImageManagerRetriever retriever = mRetrievers.get(urlString); if (mRetrievers.get(urlString) == null) {
retriever = new WebImageManagerRetriever(context, urlString, diskCacheTimeoutInSeconds, this);
mRetrievers.put(urlString, retriever);
mWaiters.add(view); Set<WebImageView> views = new HashSet<WebImageView>();
views.add(view);
mRetrieverWaiters.put(retriever, views); // start!
retriever.execute();
} else {
mRetrieverWaiters.get(retriever).add(view);
mWaiters.add(view);
}
} public void reportImageLoad(String urlString, Bitmap bitmap) {
WebImageManagerRetriever retriever = mRetrievers.get(urlString); for (WebImageView iWebImageView : mRetrieverWaiters.get(retriever)) {
if (mWaiters.contains(iWebImageView)) {
iWebImageView.setImageBitmap(bitmap);
mWaiters.remove(iWebImageView);
}
} mRetrievers.remove(urlString);
mRetrieverWaiters.remove(retriever);
} public void cancelForWebImageView(WebImageView view) {
// TODO: cancel connection in progress, too
mWaiters.remove(view);
} @Override
public void onWebImageLoad(String url, Bitmap bitmap) {
reportImageLoad(url, bitmap);
} @Override
public void onWebImageError() {
}
}

开源项目WebImageView载入图片的更多相关文章

  1. 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新

    本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...

  2. 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新

    [原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...

  3. 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新

    上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...

  4. iOS开源项目周报0105

    由OpenDigg 出品的iOS开源项目周报第四期来啦.我们的iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开发方面的开源项目,方便iOS开发人员便捷的找到自己需要的项目工具等. He ...

  5. .NET平台开源项目速览(18)C#平台JSON实体类生成器JSON C# Class Generator

    去年,我在一篇文章用原始方法解析复杂字符串,json一定要用JsonMapper么?中介绍了简单的JSON解析的问题,那种方法在当时的环境是非常方便的,因为不需要生成实体类,结构很容易解析.但随着业务 ...

  6. .NET平台开源项目速览(17)FluentConsole让你的控制台酷起来

    从该系列的第一篇文章 .NET平台开源项目速览(1)SharpConfig配置文件读写组件 开始,不知不觉已经到第17篇了.每一次我们都是介绍一个小巧甚至微不足道的.NET平台的开源软件,或者学习,或 ...

  7. .NET平台开源项目速览(16)C#写PDF文件类库PDF File Writer介绍

    1年前,我在文章:这些.NET开源项目你知道吗?.NET平台开源文档与报表处理组件集合(三)中(第9个项目),给大家推荐了一个开源免费的PDF读写组件 PDFSharp,PDFSharp我2年前就看过 ...

  8. .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验

    不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...

  9. .NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper

    好久没有写文章,工作甚忙,但每日还是关注.NET领域的开源项目.五一休息,放松了一下之后,今天就给大家介绍一个轻量级的对象映射工具Tiny Mapper:号称是.NET平台最快的对象映射组件.那就一起 ...

随机推荐

  1. LOJ#2244. 「NOI2014」起床困难综合症

    $n \leq 1e5$个位运算操作,$m \le 2^{30}$,问$0-m$中谁进行完所有操作值最大,输出这个最大值. cfA题难度?当送分题就不管了 and相当于几个位取0,or相当于几个位取1 ...

  2. shell script timer and 無限迴圈

    while : do echo " infinite loop" sleep 2; done

  3. UnionFind(PYthon实现)

    UnionFind用于解决图的连通性问题,不需要给出具体路径的情况,可用来计算连通分支数 参考链接: https://blog.csdn.net/dm_vincent/article/details/ ...

  4. mysql5.7 mysql库下面的user表没有password字段无法修改密码

    如题所述,mysql5.7  mysql库下面的user表没有password字段无法修改密码, 5.7版本已经不再使用password来作为密码的字段了  而改成了authentication_st ...

  5. 【原创】SSO-Javascript模拟IE登录,不让IIS弹出登录窗口

    解决方案: 用JS模拟IE用户登录,再跳转到对应的系统. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&q ...

  6. Linux centos 时间不同步 date 和 hwclock 时间不一致

    Linux centos 时间不同步 date 和 hwclock 网站有两台服务器,date 查看差3分钟 在应用 APP倒计时 与 直播,时时性较强的功能应用中 请求服务器后返回的服务器时间与数据 ...

  7. webview reload 错误 Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted"

    在某个特定的场合先需要对WKWebView进行一次reload,但是直接回走到失败的代理方法中并报如下的错误 Error Domain=WebKitErrorDomain Code=102 " ...

  8. 怎样在action中获得值栈ValueStack中的值

    1,实现RequestAware接口 //模拟对象    User model=new User();    user.setName=“lisi”;2,ValueStack value=(Value ...

  9. 深入Java—String源代码

    /* * @(#)String.java 1.204 06/06/09 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * ...

  10. ActiveMQ 翻译第一章 1.2小节(松耦合与ActiveMQ和何时使用ActiveMQ)

    第一章 1.2.1小节  松耦合与ActiveMQ ActiveMQ为应用程序架构提供送耦合实现组件.松耦合经常被引入到系统架构中,来减轻紧耦合的远程工程调用的使用.松耦合的设计是异步的,来自其他系统 ...