ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.util.LruCache;/*** A tool class for managing images. * * @authorTony*/ Public classImageloader {/*** The core class of image caching technology, which caches all downloaded images and removes the least recently used images when the program memory reaches the set value. */ Private StaticLrucache<string, bitmap>Mmemorycache; /*** Examples of imageloader. */ Private StaticImageloader Mimageloader; PrivateImageloader () {//get the maximum available memory for an application intMaxMemory = (int) Runtime.getruntime (). MaxMemory (); intCacheSize = MAXMEMORY/8; //set the picture cache size to the 1/8 of the program's maximum available memoryMmemorycache =NewLrucache<string, bitmap>(cacheSize) {@Overrideprotected intsizeOf (String key, Bitmap Bitmap) {returnBitmap.getbytecount (); } }; } /*** Get an instance of Imageloader. * * @returnan instance of Imageloader. */ Public StaticImageloader getinstance () {if(Mimageloader = =NULL) {Mimageloader=NewImageloader (); } returnMimageloader; } /*** Store a picture in the LRUCache. * * @paramKey * LRUCache, where the URL of the image is passed in. * @parambitmap * LRUCache key, where bitmap objects downloaded from the network are passed in. */ Public voidAddbitmaptomemorycache (String key, Bitmap Bitmap) {if(Getbitmapfrommemorycache (key) = =NULL) {mmemorycache.put (key, bitmap); } } /*** Get a picture from LRUCache and return NULL if it does not exist. * * @paramKey * LRUCache, where the URL of the image is passed in. * @returnthe bitmap object that corresponds to the incoming key, or null. */ PublicBitmap Getbitmapfrommemorycache (String key) {returnMmemorycache.get (key); } Public Static intcalculateinsamplesize (bitmapfactory.options Options,intreqwidth) { //the width of the source picture Final intwidth =Options.outwidth; intInsamplesize = 1; if(Width >reqwidth) { //calculates the ratio between the actual width and the target width Final intWidthRatio = Math.Round ((float) Width/(float) reqwidth); Insamplesize=WidthRatio; } returninsamplesize; } Public StaticBitmap Decodesampledbitmapfromresource (String pathName,intreqwidth) { //The first resolution sets Injustdecodebounds to true to get the picture size FinalBitmapfactory.options Options =Newbitmapfactory.options (); Options.injustdecodebounds=true; Bitmapfactory.decodefile (pathName, Options); //call the method defined above to calculate the Insamplesize valueOptions.insamplesize =calculateinsamplesize (options, reqwidth); //parse the picture again using the obtained insamplesize valueOptions.injustdecodebounds =false; returnbitmapfactory.decodefile (pathName, Options); }}
Tool classes for managing images