Detailed Android image three-level cache and image compression _android

Source: Internet
Author: User

Why do I need picture caching

Android defaults to allocating 16M of memory to each application, so if you load too many pictures, you should cache the images to prevent memory overflow. The three-level cache of pictures is:

    • Memory Cache
    • Local cache
    • Network cache

In which, the memory cache should be loaded first, it is the fastest, the local cache secondary first load, it is fast; the network cache should not be loaded first, it goes to the network, slow and consumption of traffic.

The concrete implementation of level three cache

Network cache

    • Load pictures According to the URL of the picture
    • Caching in local and in-memory

 public class Netcacheutils {private Localcacheutils mlocalcacheutils;

    Private Memorycacheutils mmemorycacheutils; Public Netcacheutils (Localcacheutils localcacheutils, memorycacheutils memorycacheutils) {mLocalCacheUtils
      = Localcacheutils;
    Mmemorycacheutils = memorycacheutils;  /** * Download pictures from the network * * @param ivpic * @param url/public void getbitmapfromnet (ImageView ivpic, String URL) {new Bitmaptask (). Execute (ivpic, URL);//Start Asynctask,//parameter will be in Doinback 
     Ground in/** * Handler and thread pool * First generic: Parameter type second generic: Update progress generics, third generic is onpostexecute return result *
      * */class Bitmaptask extends Asynctask<object, Void, bitmap> {private ImageView ivpic;

      Private String URL; /** * Background time consuming method is executed here, child thread/@Override protected Bitmap doinbackground (Object ... params) {i
        Vpic = (ImageView) params[0]; Url = (String) params[1];
      Ivpic.settag (URL);//Bind URL and ImageView to return Downloadbitmap (URL);
        /** * Update progress, main thread * * * @Override protected void onprogressupdate (void ... values) {
      Super.onprogressupdate (values);
        /** * After the end of the time consuming method, the main thread/@Override protected void OnPostExecute (Bitmap result) {

          if (result!= null) {String bindurl = (string) ivpic.gettag ();
            if (Url.equals (Bindurl)) {//ensures that the picture is set to the correct ImageView ivpic.setimagebitmap (result);  Mlocalcacheutils.setbitmaptolocal (URL, result);//Save picture in local mmemorycacheutils.setbitmaptomemory (URL, result);
          Save the picture in memory System.out.println ("read the picture from the network cache ..."); /** * Download picture * * @param URL * @return/private Bitmap Downloa
      Dbitmap (String URL) {HttpURLConnection conn = null; try {conn = (Httpurlconnection) new URL (URL). OpenConnection ();
        Conn.setconnecttimeout (5000);
        Conn.setreadtimeout (5000);
        Conn.setrequestmethod ("get");

        Conn.connect ();
        int responsecode = Conn.getresponsecode ();

          if (Responsecode = =) {InputStream InputStream = Conn.getinputstream ();
          Picture compression processing bitmapfactory.options option = new Bitmapfactory.options (); Option.insamplesize = 2;//width is compressed to the original One-second, this parameter needs to be displayed according to the size of the picture to determine the Option.inpreferredconfig = bitmap.config.rgb_565;//Set
          Place picture format Bitmap Bitmap = Bitmapfactory.decodestream (InputStream, NULL, option);
        return bitmap;
      } catch (Exception e) {e.printstacktrace ();
      finally {conn.disconnect ();
    return null;

 }
  }

Local cache

Two methods: Set local cache, get local cache

  public class Localcacheutils {public static final String Cache_path = environment. Getexternalstoragedire

    Ctory (). GetAbsolutePath () + "/local_cache"; /** * Read pictures from local sdcard/public Bitmap getbitmapfromlocal (string url) {try {string fileName = M
        D5encoder.encode (URL);

        File File = new file (Cache_path, fileName);
          if (file.exists ()) {Bitmap Bitmap = Bitmapfactory.decodestream (new FileInputStream (file));
        return bitmap;
      } catch (Exception e) {e.printstacktrace ();
    return null; /** * Write pictures to sdcard * * @param URL * @param bitmap/public void setbitmaptolocal (Strin

        G URL, Bitmap Bitmap) {try {String fileName = md5encoder.encode (URL);

        File File = new file (Cache_path, fileName);
        File parentfile = File.getparentfile (); if (!parentfile.exists ()) {//If the folder does not exist, create the folder ParenTfile.mkdirs ();
      //Save the picture in the local bitmap.compress (Compressformat.jpeg, new FileOutputStream (file));
      catch (Exception e) {e.printstacktrace ();

 }

    }
  }

Memory Cache

Two methods: Set memory cache, get memory cache

Problem:

If you use HashMap to store pictures, when pictures become more and more, it can cause memory overflow because it is a strong reference and the Java garbage collector will not recycle.

If you change to a soft reference softreference (the garbage collector will consider recycling), there is still a problem: in android2.3+, the system will give priority to softreference objects in advance, even if the memory is enough.

Solution: You can use LRUCache to solve the above memory does not recycle or early recovery problems. Least recentlly Use least recent algorithm it will control the memory in a certain size, exceeding the maximum will be automatically recycled, the maximum value of the developer set

    public class Memorycacheutils {//Private hashmap<string, softreference<bitmap>> Mmemorycache = n
      EW//Hashmap<string, softreference<bitmap>> ();

      Private lrucache<string, bitmap> Mmemorycache; Public Memorycacheutils () {Long maxmemory = Runtime.getruntime (). MaxMemory ()/8;//simulator defaults to 16M Mmemorycach E = new lrucache<string, bitmap> ((int) maxmemory) {@Override protected int sizeOf (String key, B Itmap value) {int byteCount = value.getrowbytes () * value.getheight ()//Get picture occupied memory size return Byteco
          Unt
      }
        };
        /** * Read from memory * * @param URL/public Bitmap getbitmapfrommemory (String URL) {
        softreference<bitmap> softreference = mmemorycache.get (URL);
        if (softreference!= null) {//Bitmap Bitmap = Softreference.get ();
        return bitmap; Return MmemoRycache.get (URL); /** * Write memory * * @param URL * @param bitmap/public void Setbitmaptomemo ry (String URL, Bitmap Bitmap) {//Softreference<bitmap> SoftReference = new//Softreference<bit
        Map> (bitmap);
        Mmemorycache.put (URL, softreference);
      Mmemorycache.put (URL, bitmap);

 }
    }

Picture compression

  Image compression processing (compress when getting pictures from the network)
  bitmapfactory.options option = new Bitmapfactory.options ();
  Option.insamplesize = 2;//width is compressed to the original One-second, this parameter needs to be displayed according to the size of the picture to determine the
  Option.inpreferredconfig = bitmap.config.rgb_565;// Set Picture format
  Bitmap Bitmap = bitmapfactory.decodestream (InputStream, NULL, option);

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.