开源项目WebImageView载入图片
项目地址: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载入图片的更多相关文章
- 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新
本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...
- 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新
[原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...
- 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新
上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...
- iOS开源项目周报0105
由OpenDigg 出品的iOS开源项目周报第四期来啦.我们的iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开发方面的开源项目,方便iOS开发人员便捷的找到自己需要的项目工具等. He ...
- .NET平台开源项目速览(18)C#平台JSON实体类生成器JSON C# Class Generator
去年,我在一篇文章用原始方法解析复杂字符串,json一定要用JsonMapper么?中介绍了简单的JSON解析的问题,那种方法在当时的环境是非常方便的,因为不需要生成实体类,结构很容易解析.但随着业务 ...
- .NET平台开源项目速览(17)FluentConsole让你的控制台酷起来
从该系列的第一篇文章 .NET平台开源项目速览(1)SharpConfig配置文件读写组件 开始,不知不觉已经到第17篇了.每一次我们都是介绍一个小巧甚至微不足道的.NET平台的开源软件,或者学习,或 ...
- .NET平台开源项目速览(16)C#写PDF文件类库PDF File Writer介绍
1年前,我在文章:这些.NET开源项目你知道吗?.NET平台开源文档与报表处理组件集合(三)中(第9个项目),给大家推荐了一个开源免费的PDF读写组件 PDFSharp,PDFSharp我2年前就看过 ...
- .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...
- .NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper
好久没有写文章,工作甚忙,但每日还是关注.NET领域的开源项目.五一休息,放松了一下之后,今天就给大家介绍一个轻量级的对象映射工具Tiny Mapper:号称是.NET平台最快的对象映射组件.那就一起 ...
随机推荐
- ckeditor自己用的配置文件config.js
原文发布时间为:2011-01-17 -- 来源于本人的百度文章 [由搬家工具导入] CKEDITOR.editorConfig = function(config) { // Define c ...
- 用正则表达式把页面中的px全部替换成rem
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- DNS+CDN
参考: 一起学DNS系列文章:http://jeffyyko.blog.51cto.com/28563/186026 CDN技术原理:http://kb.cnblogs.com/page/121664 ...
- Day 22 Object_oriented_programming 3
isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象,如果是返回True 1 class F ...
- LeetCode OJ-- Jump Game
https://oj.leetcode.com/problems/jump-game/ 从0开始,根据每一位上存的数值往前跳. 这道题给想复杂了... 记录当前位置 pos,记录可以调到的最远达位置为 ...
- 长安大学第四届“迎新杯”程序设计竞赛 H 圣诞节糖果【二分】
时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 131072K,其他语言262144K64bit IO Format: %lld 题目描述 圣诞节临近,彩虹岛的黑心商人
- POJ 3070 Fibonacci【斐波那契数列/矩阵快速幂】
Fibonacci Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 17171 Accepted: 11999 Descr ...
- JLOI2018 日志
JLOI2018 今年有幸参加吉林省的省选,考过之后在这里写一下总结和感受. DAY1: t1(chess):首先看到题目,第一想法是暴力,上来直接写了暴力,枚举所有的情况,再在这些情况里找到差值最大 ...
- spring 自定义解析类
设计配置属性和JavaBean 编写XSD文件 编写NamespaceHandler和BeanDefinitionParser完成解析工作 编写spring.handlers和spring.schem ...
- weblogic的集群与配置图文方法
一.Weblogic的集群 还记得我们在第五天教程中讲到的关于Tomcat的集群吗? 两个tomcat做node即tomcat1, tomcat2,使用Apache HttpServer做请求派发 ...