项目地址: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. Replacing Accented characters(Diacritic) .NET

    原文发布时间为:2012-02-17 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Collections.Generic;using Syste ...

  2. [LeetCode] Jump Game II 贪心

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  3. bit、byte、位、字节、汉字的关系

    字节(Byte):通常将可表示常用英文字符8位二进制称为一字节. 一个英文字母(不分大小写)占一个字节的空间,一个中文汉字占两个字节的空间. 符号:英文标点2占一个字节,中文标点占两个字节. 1字节( ...

  4. LeetCode OJ-- Substring with Concatenation of All Words ***

    https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ 找S中子串,每个元素都在T中出现了,且所有T中元 ...

  5. PHP生成随机码

    前几天,做了个小小的实验,生成了一组数据,数据要求是包含1000个元素,每个元素为10个随机的数字加字母的组合. 嗨呀,说写就写,然后用for循环生成了一组数据,看起来还不错,先把代码贴上来. //随 ...

  6. 手游LTV(用户终生价值)计算公式

    在承接APP推广项目中,手游价值变现最直接,核心是获取更多的充值,其中LTV(Lifetime-Value生命周期价值)是一个重要参考指标,可以理解为玩家在其生命周期内对游戏的平均贡献值,为什么要计算 ...

  7. 基于WPF系统框架设计(9)-多值绑定之IMultiValueConverter

    应用场景 我想把View层的一个布局控件和功能按钮传到ViewModel层,达到动态变更布局,同时灵活获取功能按钮的属性,让View和ViewModel完全分离,而不受View层影响. 最后我想到使用 ...

  8. IOS 开发之 Method Swizzling

    ios 分类中如果增加的方法与被扩展的类方法名重复,则原方法就没法被调用….看以下例子 例如: @interface ClassA : NSObject - (NSString *) myMethod ...

  9. 浅谈XXE攻击

    一.XXE,即XML External Entity,XML外部实体.ENTITY 实体,在一个甚至多个XML文档中频繁使用某一条数据,我们可以预先定义一个这条数据的“别名”,即一个ENTITY,然后 ...

  10. MFC中 SDI/MDI框架各部分指针获取方式

    VC MFC SDI/MDI框架各部分指针获取方式   整理总结一下,希望能帮助到别人.   获得CWinApp 获得CMainFrame 获得CChildFrame 获得CDocument 获得CV ...