项目地址: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. Eclipse与MyEclipse增加主题

    下载所需文件 下载地址:https://pan.baidu.com/s/1slq9lFn 如果eclipse和myeclipse里的MyEclipse 10\dropins存在features和plu ...

  2. android基本控件学习-----ImageView

    ImageView的讲解 一.src和background的区别 background我们通常理解是背景,而src是内容,当使用src填入图片的时候是以图片的大小直接填充,并不会进行拉伸,而backg ...

  3. python第三方库安装和卸载

    库的安装与卸载 pip install requests pip uninstall requests 查看安装好的库 pip list   第三方库的各种安装方式如下: 一.包管理器 Python有 ...

  4. C结构体struct用法小结

    结构体和int,float等类型一样是一种常用的类型,它是由各种基本数据类型构成,通常包含有struct关键字,结构体名,结构体成员,结构体变量. 一.结构体定义 通常有3种定义方式,以例子方式表示: ...

  5. pip源配置

    1.使用配置文件配置文件[global]trusted-host=mirrors.aliyun.comindex-url=http://mirrors.aliyun.com/pypi/simple/ ...

  6. Lotus Notes Error: your mail file cannot be located. use file location manage location to ensure that your mail file is specified correctly

    在notes客户端中,当我们切换到另一个ID的时候,通过程序发送邮件,会报错:

  7. delphi 窗体透明详解TransparentColorValue,窗体透明控件不透明

    关于窗体透明的做法 来自:http://blog.csdn.net/shuaihj/article/details/8610343 关于窗体透明的做法 1.在Delphi中,设置窗体的AlphaBle ...

  8. python--网络爬虫一

    http://hankjin.blog.163.com/blog/static/3373193720105140583594/ http://blog.csdn.net/wklken/article/ ...

  9. (9)centos下防火墙firewalld设置

    学习apache安装的时候需要打开80端口,由于centos 7版本以后默认使用firewalld后,网上关于iptables的设置方法已经不管用了,想着反正iptable也不会用,索性直接搬官方文档 ...

  10. Codeforces 766E Mahmoud and a xor trip(树形DP)

    题目链接 Mahmoud and a xor trip 树形DP.先考虑每个点到他本身的距离和,再算所有点两两距离和. 做的时候考虑二进制拆位即可. #include <bits/stdc++. ...