Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android圖片緩存技術

Android圖片緩存技術

編輯:關於Android編程

 前不久搞的Android圖片緩存,剛開始引入開源的框架,用著還行,但是在開發中遇到問題,就比如universal-image-loader-1.9.5.jar這個框架吧,在加載圖片的時候自定義imageview無法加載,可能是存在以下問題吧,況且導入框架導致開發的項目包越來越大,基於上面的這幾種情況,於是我就想自己寫一個圖片三級緩存的工具。
簡要分析:剛開始想,圖片的加載顯示無非是先檢查內存裡面有沒有,沒就去文件裡面找,若是文件裡面沒有的話就去開啟網絡下載,這樣也符合開發中的大部分需求,而且效率肯定要高一點,在某些場合如快速滑動listview時從文件中加載圖片就沒有從內存中加載得快。先來看看效果吧!
這是第一次加載出來的圖片,當然是網上的一張圖片:這裡寫圖片描述
圖片加載出來了,我們要看看日志,日志不會說謊,我截圖的日志
這裡寫圖片描述剛才是本地和內存都沒有那就的去網絡下載了,所有日志打印的是開啟網絡下載
然而第二次進入應用的時候呢?還回去開啟網絡下載嗎?那肯定不會的,要不這樣要它有啥用呢?
看看吧這就是第二次進入應用的時候的日志這裡寫圖片描述vcDPyqa9srXEtqvO96OsttS0y6Os0tTOqr7N1eK49r7NzerBy6O/ztLDx9OmuMOw0c7EvP7W0LXEzbzGrLbByKG1vcTatObW0KOs1eLR+bfA1rnP8Wxpc3R2aWV31eLR+bXEv+zL2bustq+y+sn6tcS07c67YnVnoaPPwsPmv7S/tM7S1Nq/7MvZu6y2r8qxtcTQp7n7o7o8aW1nIGFsdD0="這裡寫圖片描述" src="/uploadfile/Collfiles/20160429/20160429090308362.png" title="\" />加載的圖片都是從內存中獲取,這樣在效果上面就很好的啦!
好的,這麼好的圖片三級緩存,那到底怎麼實現的呢以及到底怎麼用的呢?下面就貼出我寫的代碼吧!讓小伙伴看看,順便優化優化!
好了,

`package com.example.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.util.Log;


/**
 * 圖片的三級緩存工具類{日後項目需要}
 * @author double 江
 *
 */
public class ImageCachceUitl {
    public static final int SUCCSEE = 0;
    public static final int FAIL = 1;
    private Context context;
    private LruCache cache;//lru算法集合,string是圖片的url,bitmap為圖片的值類型
    private File cacheDir;
    Handler handler;
    private ExecutorService executorService;//維護線性池
    public ImageCachceUitl(Context context ,Handler handler){
        this.context=context;
        this.handler=handler;
        cacheDir=context.getCacheDir();//獲得cache文件夾
        //維護幾個網絡線程下載圖片
        executorService=Executors.newFixedThreadPool(5);
        int maxSize=(int) (Runtime.getRuntime().maxMemory()/8);//獲得運行環境的內存大小的1/8
        cache=new LruCache(maxSize){
            // TODO 每存儲一張圖片的大小(作用於內存溢出丟圖片)
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //返回當前一行所占的字節數*高度,就是圖片的大小
                return value.getRowBytes()*value.getHeight();
            }
        };//當前圖片緩存總數的大小
    }
    /**
     * 
     * @param url 下載圖片的連接
     * @param position 需要顯示圖片的imgeView的Tag
     * @return
     */
    public Bitmap getBitmapFromUrl(String url,int position){
        //1內存中獲取圖片LRU算法
        Bitmap bitmap=cache.get(url);
        //內存中有指定圖片
        if (bitmap!=null) {
            Log.i("從內存中獲得圖片", "從內存中獲得圖片"+url);
            return bitmap;
        }
        //2文件中獲取圖片
        bitmap=getBitmapFromFile(url);
        if (bitmap!=null) {
            Log.i("從文件中獲得圖片", "從文件中獲得圖片"+url);
            return bitmap;
        }
        //3開啟網絡下載
        Log.i("從網絡中獲得圖片", "從網絡中獲得圖片"+url);
        getBitmapFromNet(url,position);
        return null;

    }

    /**
     * 網絡獲取圖片
     * @param url 圖片的;鏈接地址
     * @param position 需要顯示的imageview的tag
     */
    private void getBitmapFromNet(String url, int position) {

        //開啟任務
        executorService.execute(new RunnableTask(url,position));
    }
    //任務接口
    class RunnableTask implements Runnable{
        String imageUrl;
        int position;
        private HttpURLConnection httpURLConnection;
        public RunnableTask(String imageUrl, int position) {
            this.position=position;
            this.imageUrl=imageUrl;
        }

        @Override
        public void run() {
            //子線程的操作,開啟網絡下載圖片
            try {
                URL url=new URL(imageUrl);
                //請求對象
                 httpURLConnection=(HttpURLConnection) url.openConnection();
                //網絡請求的方式
                httpURLConnection.setRequestMethod("GET");
                //超時的時間,
                httpURLConnection.setConnectTimeout(5000);
                //讀取超時的時間
                httpURLConnection.setReadTimeout(5000);
                //httpURLConnection.getResponseCode()拿到最新數據
                if (httpURLConnection.getResponseCode()==200) {
                    //success get data from net;get tape 
                    InputStream inputStream=httpURLConnection.getInputStream();
                    //將流轉化成bitmap圖片
                    Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
                    //利用handler機制放入主線程中顯示
                    Message msg=new Message();
                    //需要在主線程中顯示的圖片msg.obj
                    msg.obj=bitmap;
                    msg.arg1=position;
                    //為msg設置標記
                    msg.what=SUCCSEE;
                    handler.sendMessage(msg);
                    //一,將下載完後的圖片保存到內存中
                    cache.put(imageUrl, bitmap);
                    //二,將下載完後的圖片保存到文件中
                    writeToLoce(imageUrl,bitmap);
                    return;
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            //關閉請求
            finally{
                //斷開服務器
                if (httpURLConnection!=null) {
                    httpURLConnection.disconnect();
                }               
            }
            //發送一個空消息
            handler.obtainMessage(FAIL).sendToTarget();
        }
    }
    /**
     * 圖片寫入cache文件夾下面的操作
     * @param imageUrl
     * @param bitmap
     */
    private void writeToLoce(String imageUrl, Bitmap bitmap) {
        try {
            String bitmapefilename=MD5Encoder.encode(imageUrl).substring(10);
            Log.i("bitmapefilename", bitmapefilename);
            File file=new File(cacheDir, bitmapefilename);
            FileOutputStream fileOutputStream =new FileOutputStream(file);
            //寫入文件的操作(1圖片類型2圖片質量當為100時表示不壓縮3文件流)
            bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 讀取文件中圖片的操作
     * @param url 圖片的連接地址
     * @return
     */
    private Bitmap getBitmapFromFile(String url) {
        try {
            //使用Md5工具加密截取前10個字符串
            String bitmapefilename=MD5Encoder.encode(url).substring(10);
            /**
             * 在cache文件夾下面找到指定文件
             * dir cache文件存儲路徑
             * name 文件名稱
             */
            File file=new File(cacheDir, bitmapefilename);
        //  file.mkdir();
            //FileInputStream fileInputStream=new FileInputStream(file);
            Bitmap bitmap=BitmapFactory.decodeFile(file.getPath());//完整文件路徑
            //Log.i("文件路徑", file.getPath().toString());
            //2讀取之後放入內存,提高效率
            cache.put(url, bitmap);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
`
下面就是一個使用demo了,其實很簡單`package com.example.do0me;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.util.AgbcApi;
import com.example.util.ClippingPicture;
import com.example.util.FastBlur;
import com.example.util.ImageCachceUitl;
import com.tencent.connect.avatar.c;



/**
 * 圖片三級緩存的測試+圖片上傳
 * @author double 江
 *
 */
public class MainActivity4 extends Activity {
    private ImageCachceUitl imageCachceUitl;
    private List urlList=new ArrayList();
    private Runnable runnable;
    private Handler handler =new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case ImageCachceUitl.SUCCSEE:
                Bitmap bitmap=(Bitmap) msg.obj;
                int psition=msg.arg1;
                //通過TAg加載當前的limageview
                ImageView imageView=(ImageView) listview.findViewWithTag(psition);
                if (null!=bitmap&&null!=imageView) {
                    imageView.setImageBitmap(bitmap);
                }
                break;
            case ImageCachceUitl.FAIL:
                Toast.makeText(getApplicationContext(), "下載錯誤", Toast.LENGTH_LONG).show();
            default:
                break;
            }
        };
    };
    private ListView listview;
    private SoapObject request;
    private ExecutorService executorService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        listview=(ListView) findViewById(R.id.imageviewlist);
        imageCachceUitl=new ImageCachceUitl(getApplicationContext(), handler);
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");

        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");
        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");

        urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");urlList.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");

        listview.setAdapter(new myListAdapt());
        executorService=Executors.newFixedThreadPool(5);
        executorService.execute(new Runnable() {

            @Override
            public void run() {
                getImageromSdk();
            }
        });
    }

    public String getImageFromAndroid(String arg0,String arg1, String arg2){
        Log.i("進入端口方法", "進入端口方法");
        final String methodName="getImageFromAndroid";
        final String soapAction=AgbcApi.NAMESPACE+methodName;
        request = new SoapObject(AgbcApi.NAMESPACE, methodName);
        request.addProperty("arg0",arg1);   
        request.addProperty("arg1",arg2);
        SoapSerializationEnvelope envelope  = new SoapSerializationEnvelope(SoapEnvelope.VER11);    
        (new MarshalBase64()).register(envelope);       
        envelope.bodyOut = request;  
        envelope.dotNet=false;
        envelope.setOutputSoapObject(request);      
        HttpTransportSE ht = new HttpTransportSE(AgbcApi.TASKSERVICEURL);  
        ht.debug=true;  
        try {

            ht.call(soapAction, envelope);
            Log.i("請求", envelope.bodyIn.toString());
        } catch (IOException | XmlPullParserException e) {
            e.printStackTrace();
        }
        return arg1;

    };

    @SuppressLint("SdCardPath")
    public  void getImageromSdk(){
        Log.i("進入獲取圖片方法", "進入獲取圖片方法");
        try{
            String srcUrl = "/sdcard/"; //路徑
            String fileName = "1.png";  //文件名
            String filrName2="2.jpg";
        ListimageList=new ArrayList<>();
        imageList.add(fileName);
        imageList.add(filrName2);       
        for (int i = 0; i < imageList.size(); i++) {
            FileInputStream fis = new FileInputStream(srcUrl + imageList.get(i));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int count = 0;
            while((count = fis.read(buffer)) >= 0){
                baos.write(buffer, 0, count);
            }
            String uploadBuffer = new String(Base64.encode(baos.toByteArray(),  Base64.DEFAULT));  //進行Base64編碼
            String methodName = "uploadImage";          
                getImageFromAndroid(methodName,imageList.get(i), uploadBuffer);   //調用webservice        
            Log.i("connectWebService", "start");    
            fis.close();
}
        }catch(Exception e){
            e.printStackTrace();
        }       
    }
    class myListAdapt extends BaseAdapter{
        private LayoutInflater layoutInflater;
        ImageView list_imag;
        Button list_but;
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return urlList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return urlList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @SuppressLint({ "InflateParams", "ViewHolder" })
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            layoutInflater=LayoutInflater.from(getApplication());
            //if (layoutInflater==null) {
            convertView = layoutInflater.inflate(R.layout.image_list_item, null);
            //  }
            list_but=(Button) convertView.findViewById(R.id.list_but);
            list_imag=(ImageView) convertView.findViewById(R.id.list_imag);

            list_imag.setTag(position);
            final Bitmap bitmap=imageCachceUitl.getBitmapFromUrl(urlList.get(position), position);
            if (null!=bitmap) {
                list_imag.setImageBitmap(bitmap);
            }
            list_imag.setVisibility(View.VISIBLE);

            list_but.setOnClickListener(new OnClickListener() {



                @Override
                public void onClick(View v) {
                    //urlList.get(position);
                    Log.i("獲取點擊焦點", "獲取點擊焦點");
                    //  getImageromSdk();
                    //startRun();
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            getImageromSdk();                           
                        }
                    }).start();
                }
            });
            return convertView;
        }

    }

}`

大概就是些吧!還沒有 吃飯。。。。走了去早吃飯了,不能太玩命了

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved