Open-source project WebImageView

Source: Internet
Author: User
Tags md5 hash


Project address: https://github.com/ZaBlanc/WebImageView


The author encapsulates the memory cache and disk cache of images and images.

The amount of code is small, but it can load images normally.

First look at the project structure:



In my opinion, you need to take a closer look at this if you want to implement it on your own.

/***** @ Param urlString the network address of the corresponding image * @ return */private String hashURLString (String urlString) {try {// Create MD5 Hash MessageDigest = 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]", "#");}

And file stream operations here

@ Overrideprotected Bitmap doInBackground (Void... params) {// check mem cache first from the memory to find Bitmap bitmap = mCache. getBitmapFromMemCache (mURLString); // check disk cache first and then find if (bitmap = null) {bitmap = mCache from the disk. getBitmapFromDiskCache (mContext, mURLString, mDiskCacheTimeoutInSeconds); if (bitmap! = Null) {// After obtaining it, add it to the memory and cache it for mCache. addBitmapToMemCache (mURLString, bitmap) ;}}if (bitmap = null) {InputStream is = null; FlushedInputStream fiis = null; try {URL url = new URL (mURLString ); URLConnection conn = url. openConnection (); is = conn. getInputStream (); FCM = new FlushedInputStream (is); bitmap = BitmapFactory. decodeStream (FCM); // 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! After completion, the callback will go back to 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 ;}}


Attached source code:

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 Sof Tware isfurnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be encoded 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 particle 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. inputStrea M; 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;/*** class for processing image cache **/public class WebImageCache {private final s Tatic String TAG = WebImageCache. class. getSimpleName (); // cache rules/*** whether to allow memory cache */private static boolean mIsMemoryCachingEnabled = true; /*** whether to allow disk caching */private static boolean mIsDiskCachingEnabled = true;/*** default timeout display time */private static int mdefadiskdiskcachetimeoutinseconds = 60*60*24; // one day default/*** cache soft drink? What about weak references ?? */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. ");}/*** retrieve the image URL from the cache * @ param urlString corresponding to the image. In the cache, the key * @ return */public Bitmap getBitmapFromMemCache (String urlString) {if (mIsMemoryCachingEnabled) {// synchronous cache synchronized (mMemCache) {SoftRefer Ence <Bitmap> bitmapRef = mMemCache. get (urlString); if (bitmapRef! = Null) {Bitmap bitmap = bitmapRef. get (); if (bitmap = null) {// if the Bitmap corresponding to the key is null, T is dropped. Remove invalid value 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 ;} /*** obtain the cached image from the disk * @ 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 ensures correct timeout settings if (diskCacheTimeoutInSeconds <0) {diskCacheTimeoutInSeconds = timeout ;} 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, "cocould not retrieve" + urlString + "from disk cache:" + ex. toString ();} finally {try {is. close () ;}catch (Exception ex) {}}} return bitmap;} return null ;} /*** Add the image to the cache * @ param urlString corresponding http network address * @ param bitmap corresponding Bitmap object */public void addBitmapToMemCache (String urlString, Bitmap bitmap) {if (mIsMemoryCachingEnabled) {synchronized (mMemCache) {mMemCache. put (urlString, new SoftReference <Bitmap> (bitmap ));}}} /*** add images to the disk cache * @ 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 (); // compress the image into bitmap. compress (Bitmap. compressFormat. PNG, 100, OS); OS. flush (); OS. close (); // NOWORKY tmpFile. renameTo (file);} catch (Exception ex) {Log. e (TAG, "cocould not store" + urlString + "to disk cache:" + ex. toString ();} finally {try {OS. close ();} catch (Exception ex) {}}}/***** @ param urlString the network address of the image * @ 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 Sof Tware isfurnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be encoded 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 particle 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. U RL; 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;/***** obtain images asynchronously */public class WebImageManagerRetriever extends AsyncTask <Void, Void, Bitmap> {private final static String TAG = WebImageManagerRetriever. cl Ass. getSimpleName (); // cacheprivate static WebImageCache mCache; // what we re looking forprivate Context mContext; private String mURLString; private int mDiskCacheTimeoutInSeconds; /*** callback */private OnWebImageLoadListener mListener; static {mCache = new WebImageCache ();} public listener (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 from the memory to find Bitmap bitmap = mCache. getBitmapFromMemCache (mURLString); // check disk cache first and then find if (bitmap = null) {bitmap = mCache from the disk. getBitmapFromDiskCache (mContext, mURLString, mDiskCacheTimeoutInSe Conds); if (bitmap! = Null) {// After obtaining it, add it to the memory and cache it for mCache. addBitmapToMemCache (mURLString, bitmap) ;}}if (bitmap = null) {InputStream is = null; FlushedInputStream fiis = null; try {URL url = new URL (mURLString ); URLConnection conn = url. openConnection (); is = conn. getInputStream (); FCM = new FlushedInputStream (is); bitmap = BitmapFactory. decodeStream (FCM); // 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! After completion, the callback will go back to 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 Sof Tware isfurnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be encoded 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 particle 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 androi D. 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, Metadata> 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 <WebImage ManagerRetriever, Set <WebImageView> (); mWaiters = new HashSet <WebImageView> ();} /*** process multiple concurrently Loaded Images * @ 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) = nul L) {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.exe cute ();} 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 (){}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.