How does imageLoader load templates? imageloader templates

Source: Internet
Author: User

How does imageLoader load templates? imageloader templates

MD5 tool:

Package com. bwie. dongchangqi. tinkertest; import java. security. MessageDigest; import java. security. NoSuchAlgorithmException;/*** Created by Administrator on 0019.*/Public class Md5Utils {/** 1. An instance using the basic class * MessageDigest object is initialized. This object uses the update method to process data. * You can call the reset method to reset the Summary at any time. * Once all the data to be updated has been updated, call one of the digest methods to complete hash calculation. * For a specified number of updated data, the digest method can be called only once. * After digest is called, The MessageDigest object is reset to its initial state. */Public static String md5 (String context) {try {MessageDigest md = MessageDigest.GetInstance("MD5"); md. update (context. getBytes (); // update Processing byte [] encryContext = md. digest (); // call this method to calculate int I; StringBuffer buf = new StringBuffer (""); for (int offset = 0; offset <encryContext. length; offset ++) {// convert (hexadecimal) I = encryContext [offset]; if (I <0) I + = 256; if (I <16) buf. append ("0"); buf. append (Integer.ToHexString(I);} return buf. toString (); // 32-bit encryption} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return null ;}}
Secondary Sampling:
Package com. bwie. dongchangqi. tinkertest; import android. graphics. Bitmap; import android. graphics. BitmapFactory; import java. io. FileDescriptor; import java. io. InputStream;/*** Created by Administrator on 0019.*/Public class ImageResizer {private static final StringTAG= "ImageResizer"; public static Bitmap compressBitmap (FileDescriptor fd, int targetWidth, int targetHeight) {Bitmap bitmap = null; if (targetWidth = 0 | targetHeight = 0) {bitmap = BitmapFactory.DecodeFileDescriptor(Fd); return bitmap;} BitmapFactory. options options = new BitmapFactory. options (); // At the beginning, only the width and height information options of the image will be loaded. inJustDecodeBounds = true; // load the image and place the width and height information in the option BitmapFactory.DecodeFileDescriptor(Fd, null, options); // retrieves the original width and height of the image. int outWidth = options. outWidth; int outHeight = options. outHeight; // calculate the zoom ratio. int inSampleSize =GetResizerRate(OutWidth, outHeight, targetWidth, targetHeight); // sets the zoom ratio options. inSampleSize = inSampleSize; // loads the specific content of the image, not just the width and height information options. inJustDecodeBounds = false; // set the color mode of the image output-RGB_565 options. inPreferredConfig = Bitmap. config.RGB_565; // Load bitmap = BitmapFactory based on the calculated ratio of the image.DecodeFileDescriptor(Fd, null, options); return bitmap;} public static Bitmap compressBitmap (InputStream inputStream, int targetWidth, int targetHeight) {Bitmap bitmap = null; if (targetWidth = 0 | targetHeight = 0) {bitmap = BitmapFactory.DecodeStream(InputStream); return bitmap;} BitmapFactory. options options = new BitmapFactory. options (); // At the beginning, only the width and height information options of the image will be loaded. inJustDecodeBounds = true; // load the image and place the width and height information in the option BitmapFactory.DecodeStream(InputStream, null, options); // retrieves the original width and height of the image. int outWidth = options. outWidth; int outHeight = options. outHeight; // calculate the zoom ratio. int inSampleSize =GetResizerRate(OutWidth, outHeight, targetWidth, targetHeight); // sets the zoom ratio options. inSampleSize = inSampleSize; // loads the specific content of the image, not just the width and height information options. inJustDecodeBounds = false; // set the color mode of the image output-RGB_565 options. inPreferredConfig = Bitmap. config.RGB_565; // Load bitmap = BitmapFactory based on the calculated ratio of the image.DecodeStream(InputStream, null, options); return bitmap;} public static Bitmap compressBitmap (String filePath, int targetWidth, int targetHeight) {Bitmap bitmap = null; if (targetWidth = 0 | targetHeight = 0) {bitmap = BitmapFactory.DecodeFile(FilePath); return bitmap;} BitmapFactory. options options = new BitmapFactory. options (); // At the beginning, only the width and height information options of the image will be loaded. inJustDecodeBounds = true; // load the image and place the width and height information in the option BitmapFactory.DecodeFile(FilePath, options); // retrieves the original width and height of the image. int outWidth = options. outWidth; int outHeight = options. outHeight; // calculates the zoom ratio. int inSampleSize =GetResizerRate(OutWidth, outHeight, targetWidth, targetHeight); // sets the zoom ratio options. inSampleSize = inSampleSize; // loads the specific content of the image, not just the width and height information options. inJustDecodeBounds = false; // set the color mode of the image output-RGB_565 options. inPreferredConfig = Bitmap. config.RGB_565; // Load bitmap = BitmapFactory based on the calculated ratio of the image.DecodeFile(FilePath, options); return bitmap ;}/***Calculate the compression ratio of the image.     **@ Return */    Private static int getResizerRate (int outWidth, int outHeight, int targetWidth, int targetHeight) {// officially recommended by Google, the compression ratio should be 2 to the exponential power int inSampleSize = 1; // if the image width and height are greater than the target width and height, perform the following operations, until our size conditions are met while (targetWidth <outWidth/inSampleSize | targetHeight <outHeight/inSampleSize) {inSampleSize * = 2;} return inSampleSize ;}}

Use local files directly for the LruCache class,

ImageLoader three-level cache to load images:

Package com. bwie. dongchangqi. tinkertest; import android. content. context; import android. graphics. bitmap; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. support. v4.util. lruCache; import android. text. textUtils; import android. util. log; import android. widget. imageView; import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileDescriptor; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java. util. concurrent. linkedBlockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;/*** Created by WuXirui* Create Time: 2018/1/4* Description:*/Public class ImageLoader {private static final StringTAG= "ImageLoader"; // The available memory space of the current app, private static intMAX_VALUABLE_MEMORY= (Int) (Runtime.GetRuntime(). MaxMemory ()/1024); // 1/8 of the currently available memory is used as the memory cache space private static intMAX_MEMORY_SIZE=MAX_VALUABLE_MEMORY/8; // disk cache space private static intMAX_DISK_SIZE= 50*1024*1024; // number of core threads private static intCORE_THREAD_SIZE= 0; // maximum number of threads private static intMAX_THREAD_SIZE= Integer.MAX_VALUE; // Survival time private static longKEEPALIVE_TIME= 60L; // index private static int cached by the diskFLAG_DISK_INDEX= 0; // stream buffer value private static intCACHE_BUFFER= 8*1024; private static final intMESSAGE_RECEIVE_RESULT= 0x123; private static volatile ImageLoaderInstance; Private Context context; private LruCache
 
  
MemoryCache; private DiskLruCache diskCache; // disk cache path private File cacheDic; // The loaded thread pool private static ThreadPoolExecutor
  ThreadPoolExecutor; Static {
  ThreadPoolExecutor= New ThreadPoolExecutor (
  CORE_THREAD_SIZE,
  MAX_THREAD_SIZE,
  KEEPALIVE_TIME, TimeUnit.
  SECONDS, New parameter blockingqueue
  
   
();} Private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); switch (msg. what) {case
   MESSAGE_RECEIVE_RESULT: ResultLoader result = (ResultLoader) msg. obj; ImageView imageView = result. imageView; Bitmap bitmap = result. bitmap; // if (bitmap! = Null) {// imageView. setImageBitmap (bitmap); //} if (imageView. getTag (). equals (result. url) {if (bitmap! = Null) {imageView. setImageBitmap (bitmap) ;}} break ;}}; private ImageLoader (Context context) {this. context = context; Log.
   I(
   TAG, "ImageLoader: size =" +
   MAX_MEMORY_SIZE); MemoryCache = new LruCache
   
    
(
    MAX_MEMORY_SIZE) {@ Override protected int sizeOf (String key, Bitmap value) {return value. getRowBytes () * value. getHeight ()/1024 ;}}; cacheDic = getCacheDic (context); try {diskCache = DiskLruCache.
    Open(CacheDic, 1, 1,
    MAX_DISK_SIZE);} Catch (IOException e) {e. printStackTrace () ;}} public static ImageLoader getInstance (Context context) {if (
    Instance= Null) {synchronized (ImageLoader. class) {if (null =
    Instance){
    Instance= New ImageLoader (context) ;}} return
    Instance;} Private File getCacheDic (Context context) {// if the SD card is available, it will be cached in the SD card if (Environment.
    GetExternalStorageState(). Equals (Environment.
    MEDIA_MOUNTED) {Return context. getExternalCacheDir ();} else {// If the SD card is unavailable, return context exists in the body storage. getCacheDir () ;}} public void display (ImageView imageView, String url) {display (imageView, url, 0, 0);} public void display (final ImageView imageView, final String url, final int targetWidth, final int targetHeight) {// prevents image misplacement and adds the Image view ID. setTag (url); // determines whether Bitmap bitmap = hasBitmapInMemory (url ); If (bitmap! = Null) {Log.
    I(
    TAG, "Memory cache 1"); imageView. setImageBitmap (bitmap); return;} // This cache does not contain Runnable runnable = new Runnable () {@ Override public void run () {Log.
    I(
    TAG, "Thread loading"); Bitmap bmp = loadBitmap (imageView, url, targetWidth, targetHeight); ResultLoader result = new ResultLoader (imageView, url, bmp); Message msg = handler. obtainMessage (); msg. what =
    MESSAGE_RECEIVE_RESULT; Msg. obj = result; msg. sendToTarget ();}};
    ThreadPoolExecutor. Execute (runnable );}
    /**
    *
    Attach Images
         
    *
    *
    @ Param
    Url
         
    */
        Private Bitmap loadBitmap (ImageView imageView, String url, int targetWidth, int targetHeight) {// judge Bitmap bitmap = hasBitmapInMemory (url) in memory again; if (bitmap! = Null) {Log.
    I(
    TAG, "Memory cache 2"); return bitmap;} // if there is no image in the memory cache, read bitmap = getBitmapFromDisk (url, targetWidth, targetHeight) from the disk cache ); if (bitmap! = Null) {Log.
    I(
    TAG, "Disk cache"); return bitmap;} // if there are no images in the disk cache, obtain try {bitmap = getBitmapFromHttp (url, targetWidth, targetHeight) from the network ); if (bitmap! = Null) {Log.
    I(
    TAG, "Network cache"); return bitmap;} catch (Exception e) {e. printStackTrace (); return null ;}
    /**
    *
    Retrieving images from the network
         
    *
    *
    @ Param
    Url
         
    *
    @ Return
     
    */
        Private Bitmap getBitmapFromHttp (String url, int targetWidth, int targetHeight) throws Exception {// Save the downloaded image to the disk, then, retrieve String uniqueKey = getUniqueKey (url); Log from the disk cache.
    I(
    TAG, "UniqueKey:" + uniqueKey); DiskLruCache. Editor edit = diskCache. edit (uniqueKey); OutputStream outputStream = edit. newOutputStream (
    FLAG_DISK_INDEX); If (downloadUrlToDiskCache (url, outputStream) {diskCache. flush (); edit. commit (); Bitmap bitmap = getBitmapFromDisk (url, targetWidth, targetHeight); memoryCache. put (uniqueKey, bitmap); return bitmap;} else {return null ;}}
    /**
    *
    Download the network image and save it to the output stream of the disk cache
         
    *
    *
    @ Param
    Url
         
    *
    @ Param
    OutputStream
         
    */
        Private boolean downloadUrlToDiskCache (String url, OutputStream outputStream) throws Exception {OkHttpClient client = new OkHttpClient (); Request request = new Request. builder (). url (url ). get (). build (); Call call = client. newCall (request); Response response = call.exe cute (); InputStream inputStream = response. body (). byteStream (); BufferedOutputStream bos = new BufferedOutputStream (outputStream); BufferedInputStream bis = new BufferedInputStream (inputStream); int length = 0; byte [] buffer = new byte [
    CACHE_BUFFER]; While (length = bis. read (buffer, 0, buffer. length ))! =-1) {bos. write (buffer, 0, length);} bos. flush (); bos. close (); bis. close (); inputStream. close (); outputStream. close (); return true ;}
    /**
    *
    Retrieve data from disk cache
         
    *
    *
    @ Param
    Url
         
    *
    @ Return
     
    */
        Private Bitmap getBitmapFromDisk (String url, int targetWidth, int targetHeight) {String uniqueKey = getUniqueKey (url); Log.
    I(
    TAG, "GetBitmapFromDisk: uniqueKey:" + uniqueKey); if (! TextUtils.
    IsEmpty(UniqueKey) {try {DiskLruCache. Snapshot snapshot = diskCache. get (uniqueKey); if (snapshot = null) {return null;} InputStream inputStream = snapshot. getInputStream (
    FLAG_DISK_INDEX); FileInputStream FCM = (FileInputStream) snapshot. getInputStream (
    FLAG_DISK_INDEX); FileDescriptor fd = fd. getFD (); // Bitmap bitmap = BitmapFactory. decodeStream (inputStream); Bitmap bitmap = ImageResizer.
    CompressBitmap(Fd, targetWidth, targetHeight); if (bitmap = null) {Log.
    I(
    TAG, "Bitmap is null");} // write to the memory cache saveBitmapToMemoryCache (url, bitmap); return bitmap;} catch (IOException e) {e. printStackTrace (); return null ;}
    /**
    *
    Save
    Bitmap
    To memory cache
         
    *
    *
    @ Param
    Url
         
    *
    @ Param
    Bitmap
         
    */
        Private void saveBitmapToMemoryCache (String url, Bitmap bitmap) {if (hasBitmapInMemory (url) = null & bitmap! = Null) {String uniqueKey = getUniqueKey (url); Log.
    I(
    TAG, "SaveBitmapToMemoryCache: 11111"); memoryCache. put (uniqueKey, bitmap); Log.
    I(
    TAG, "SaveBitmapToMemoryCache:" + memoryCache. get (uniqueKey ));}}
    /**
    *
    Check whether the cache exists in the memory cache.
         
    *
    *
    @ Param
    Url
         
    *
    @ Return
     
    */
        Private Bitmap hasBitmapInMemory (String url) {String uniqueKey = getUniqueKey (url); if (! TextUtils.
    IsEmpty(UniqueKey) {return memoryCache. get (uniqueKey);} return null ;}
    /**
    *
    Obtain
    Url
    Unique Identifier
         
    *
    *
    @ Param
    Text
         
    *
    @ Return
     
    */
        Private String getUniqueKey (String text) {return Md5Utils.
    Md5(Text);} private static class ResultLoader {private ImageView imageView; private String url; private Bitmap bitmap; public ResultLoader (ImageView imageView, String url, Bitmap bitmap) {this. imageView = imageView; this. url = url; this. bitmap = bitmap ;}}}
   
  
 

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.