開源項目WebImageView載入圖片

來源:互聯網
上載者:User


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


作者對載入圖片,以及圖片的記憶體緩衝和磁碟緩衝做了封裝。

代碼量不多,但是能夠滿足一般的載入圖片。

先看下項目結構:



我認為通常情況下自己去實現的話,這點需要仔細看下。

/** *  * @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]", "#");}

以及這裡的檔案流操作

@Overrideprotected 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);// cacheif (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;}@Overrideprotected 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);}@Overridepublic 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 VenicePermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE 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 cacheaddBitmapToMemCache(urlString, bitmap);// disk cache// TODO: manual cache cleanupif (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 VenicePermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE 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();// cacheprivate static WebImageCache mCache;// what we're looking forprivate 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;}@Overrideprotected 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);// cacheif (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;}@Overrideprotected 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);}@Overridepublic 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 VenicePermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE 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 inprivate 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, toomWaiters.remove(view);}    @Override    public void onWebImageLoad(String url, Bitmap bitmap) {        reportImageLoad(url, bitmap);    }    @Override    public void onWebImageError() {    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.