开源项目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平台最快的对象映射组件.那就一起 ...
随机推荐
- mvc filters
1.controller using System; using System.Collections.Generic; using System.Linq; using System.Web; us ...
- H5 <audio> 音频标签自定义样式修改以及添加播放控制事件
H5 <audio> 音频标签自定义样式修改以及添加播放控制事件 Dandelion_drq 关注 2017.08.28 14:48* 字数 331 阅读 2902评论 3喜欢 3 说明: ...
- Codeforces 791D Bear and Tree Jump(树形DP)
题目链接 Bear and Tree Jumps 考虑树形DP.$c(i, j)$表示$i$最少加上多少后能被$j$整除. 在这里我们要算出所有$c(i, k)$的和. 其中$i$代表每个点对的距离, ...
- Light oj 1095 - Arrange the Numbers (组合数学+递推)
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1095 题意: 给你包含1~n的排列,初始位置1,2,3...,n,问你刚好固定 ...
- Graphs (Cakewalk) 1 B - medium
Discription Bear Limak examines a social network. Its main functionality is that two members can bec ...
- 小菜的系统框架界面设计-XiaoCai.WinformUI代码开源
我的源码分享 曾经,看到别人漂亮的系统界面,合理的布局,可是却没有提供源码,道理很简单,就是有偿提供,实际上对于有些技巧的东西也并没有多么难,只是不懂原理,感觉到困难罢了. 而对于刚毕业的我,求知欲强 ...
- innodb事务锁
计算机程序锁 控制对共享资源进行并发访问 保护数据的完整性和一致性 lock 主要是事务,数据库逻辑内容,事务过程 latch/mutex 内存底层锁: 更新丢失 原因: B的更改还没有 ...
- 关于Android内存优化你应该知道的一切
介绍 在Android系统中,内存分配与释放分配在一定程度上会影响App性能的—鉴于其使用的是类似于Java的GC回收机制,因此系统会以消耗一定的效率为代价,进行垃圾回收. 在中国有句老话:”由俭入奢 ...
- 某音乐类App评论相关API的分析及SQL注入尝试
关键字:APIfen.工具使用.sql注入 涉及工具/包:Fiddler.Burpsuite.Js2Py.Closure Compiler.selenium.phantomjs.sqlmap 摘要: ...
- Linux 设备驱动模型
Linux系统将设备和驱动归一到设备驱动模型中了来管理 设备驱动程序功能: 1,对硬件设备初始化和释放 2,对设备进行管理,包括实参设置,以及提供对设备的统一操作接口 3,读取应用程序传递给设备文件的 ...