Open source project Webimageview loading pictures

Source: Internet
Author: User
Tags md5 hash


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


The author encapsulates the loading of images, as well as the memory caches and disk caches of images.

The amount of code is not much, but can satisfy the general loading picture.

First look at the project structure:



I think this is something that needs to be looked at in the usual circumstances.

/** *  * @param urlstring network address for image * @return */private string hashurlstring (String urlstring) {    try {        //creat E 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]", "#");}

And here's the file stream operation

@Overrideprotected Bitmap doinbackground (Void ... params) {//Check mem cache first finds Bitmap Bitmap = Mcache.getbitmap from memory Frommemcache (murlstring);//Check disk cache first then find if (bitmap = = null) {bitmap = Mcache.getbitmapfromdiskcache ( Mcontext, murlstring,mdiskcachetimeoutinseconds); if (bitmap! = null) {//gets added to the in-memory cache 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! after completion callback back 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 B ytesskipped = In.skip (n-totalbytesskipped), if (bytesskipped = = 0L) {int b = read (), if (b < 0) {break;//We reached E of else {bytesskipped = 1;///We read one byte}}totalbytesskipped + = bytesskipped;} return totalbytesskipped;}}


Attach Source code:

Webimagecache


/*copyright (c) Rapture in Venicepermission are hereby granted, free of charge, to all person obtaining a copyof this Software and associated documentation files (the "Software"), to dealin the software without restriction, including Withou T limitation the Rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the software, an D to permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above copyright not Ice and this permission notice shall being included inall copies or substantial portions of the Software.the software is Prov IDed "As is", without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of Merchantabil Ity,fitness for A particular PURPOSE and noninfringement.  In NO EVENT shall theauthors or COPYRIGHT holders is 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 softwareor 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;/** * Processing Picture Cache class * */public class Webimagecache {private final static String TAG = WebImageCache.class.getS Implename ();//Cache rules/** * Whether to allow memory cache */private static Boolean mismemorycachingenabled = true;/** * Allow disk cache */private static Boolean misdiskcachingenabled = true;/** * Default timeout display time */private static int mdefaultdiskcachetimeoutinseconds = 60 * 60 * 24; One day default/** * Cache soft drink? Well, 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."); /** * Remove picture from cache * @param urlstring URL of the corresponding image, key in cache * @return */public Bitmap getbitmapfrommemcache (String urlstring) {i F (mismemorycachingenabled) {//Sync cache synchronized (mmemcache) {softreference<bitmap> bitmapref = Mmemcache.get ( urlstring); if (bitmapref! = null) {Bitmap Bitmap = Bitmapref.get (); if (Bitmap = = null) {//key corresponds to Bitmap is empty, then 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;} /** * Get cached pictures from disk * @param context * @param urlstring * @param diskcachetimeoutinseconds * @return */public Bitmap Getbitma Pfromdiskcache (context context, String urlstring, int diskcachetimeoutinseconds) {if (misdiskcachingenabled) {Bitmap bitmap = null;        File path = Context.getcachedir ();        InputStream is = null;                String hashedurlstring = hashurlstring (urlstring); Correct timeout guarantees the correct timeout setting if (Diskcachetimeoutinseconds < 0) {diskcachetimeoutinseconds = Mdefaultdisk        Cachetimeoutinseconds;        } File File = New file (path, hashedurlstring); if (file.exists () && file.canread ()) {//Check for timeout if ((file.lastmodified () + (Diskcachetim Eoutinseconds * 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;} /** * Add picture to cache * @param urlstring corresponding HTTP network address * @param bitmap corresponding Bitmap object */public void Addbitmaptomemcache (String urlstri Ng, Bitmap Bitmap) {if (mismemorycachingenabled) {synchronized (Mmemcache) {mmemcache.put (urlstring, New softreference& Lt Bitmap> (Bitmap));}} /** * Add pictures 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 images for bitmap.compress (Bitmap.CompressFormat.PNG, +, 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 corresponding to the network address of the picture * @return */private string hashurlstring (string ur      lstring) {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) Rapture in Venicepermission are hereby granted, free of charge, to all person obtaining a copyof this Software and associated documentation files (the "Software"), to dealin the software without restriction, including Withou T limitation the Rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the software, an D to permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above copyright not Ice and this permission notice shall being included inall copies or substantial portions of the Software.the software is Prov IDed "As is", without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of Merchantabil Ity,fitness for A particular PURPOSE and noninfringement.  In NO EVENT shall theauthors or COPYRIGHT holders is 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 softwareor 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;/** * * Asynchronously get Picture */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;/** * Callback */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 finds Bitmap Bitmap = Mcache.getbitmap from memory Frommemcache (murlstring);//Check disk cache first then find if (bitmap = = null) {bitmap = Mcache.getbitmapfromdiskcache ( Mcontext, murlstring,mdiskcachetimeoutinseconds); if (bitmap! = null) {//gets added to the in-memory cache 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! after completion callback back if (null! = Mlistener) {if (null = = Bitmap) {MLIs Tener.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 B ytesskipped = In.skip (n-totalbytesskipped), if (bytesskipped = = 0L) {int b = read (), if (b < 0) {break;//We reached E of else {bytesskipped = 1;///We read one byte}}totalbytesskipped + = bytesskipped;} return totalbytesskipped;}} Public interface Onwebimageloadlistener {public void onwebimageload (String url, Bitmap Bitmap);p ublic void Onwebimageerror ();}}

Webimagemanager

/*copyright (c) Rapture in Venicepermission are hereby granted, free of charge, to all person obtaining a copyof this Software and associated documentation files (the "Software"), to dealin the software without restriction, including Withou T limitation the Rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the software, an D to permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above copyright not Ice and this permission notice shall being included inall copies or substantial portions of the Software.the software is Prov IDed "As is", without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of Merchantabil Ity,fitness for A particular PURPOSE and noninfringement.  In NO EVENT shall theauthors or COPYRIGHT holders is 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 softwareor 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 a image to load InPrivate M Ap<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> ();} /** * Handles multiple simultaneous loading pictures * @param context * @param urlstring * @param view * @param diskcachetimeoutinseconds */public void Downlo Adurl (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 () {}}


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.