一个简单的LruImageLoader

1.代码:


import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * 加密图片加载及下载v2:
 * 1.对比v1添加了加载图片逻辑
 * 2.对比v1先保存图片再从文件获取图片,防止图片比较大导致OOM
 *
 * 使用示例:
 * //必须先调用init
 * LruImageLoader.getInstance().init(getApplication());
 *
 * LruImageLoader.getInstance().loadCacheImage("https://pics2.baidu.com/feed/d043ad4bd11373f07cfedf093f1d9bfcfaed0479.jpeg?token=de18eb3030df73681a7ee453fb698651&s=95A742B60A9168CEE4BF9D7A03009018", image_view)
 *
 * TODO 添加图片显示动画
 */
public class LruImageLoader {

    private volatile LruCache<String, WeakReference<Bitmap>> mImageCache = new LruCache<>(100);

    private Context applicationContext;

    private static LruImageLoader instance;

    private ExecutorService executorService;

    public static LruImageLoader getInstance() {
        if (instance == null) {
            synchronized (LruImageLoader.class) {
                if (instance == null) {
                    instance = new LruImageLoader();
                }
            }
        }
        return instance;
    }

    public void init(Application applicationContext) {
        if (this.applicationContext == null) {
            this.applicationContext = applicationContext;
            executorService = Executors.newFixedThreadPool(10);
        }
    }

    private LruImageLoader() { }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

    /**
     * 加载图片(缓存),无加载图片及错误图片参数
     */
    public void loadCacheImage(String url, ImageView imageView) {
        loadCacheImage(url, imageView, -1, -1);
    }

    /**
     * 加载图片(缓存),带加载及错误图片参数
     */
    public void loadCacheImage(String url, ImageView imageView, int errorImgId, int loadImgId) {
        String imageID = getImageName(url);
        WeakReference<Bitmap> weakReference = mImageCache.get(imageID);
        if (weakReference != null && weakReference.get() != null) {
            if (imageView != null) {
                imageView.setImageBitmap(weakReference.get());
            }
        } else if (new File(applicationContext.getExternalCacheDir() + File.separator + imageID).exists()) {
            Bitmap bitmap = loadImage(imageID, imageView == null? 2:imageView.getMeasuredWidth());

            //加入缓存
            mImageCache.put(imageID, new WeakReference<>(bitmap));

            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        } else {
            if (errorImgId > 0) {
                downloadImage(url, imageID, errorImgId, loadImgId,  imageView);
            } else {
                downloadImage(url, imageID, imageView);
            }
        }
    }

    private volatile Map<String, ImageView> imageViewMap = new HashMap<>(100);

    public void downloadImage(String url, final String imageID, ImageView imageView) {
        downloadImage(url, imageID, -1, -1, imageView);
    }

    /**
     * 下载图片任务
     */
    public void downloadImage(final String url, final String imageID, final int errorImgId, int loadImgId, ImageView imageView) {
        //开始加载图片,
        if (loadImgId > 0) {
            imageView.setImageResource(loadImgId);
        }

        if (!imageViewMap.containsKey(imageID)) {
            Set<String> keySet = imageViewMap.keySet();
            for (String key:keySet) {
                if (imageViewMap.get(key) == imageView) {
                    imageViewMap.remove(key);
                    break;
                }
            }
            imageViewMap.put(imageID, imageView);
        }

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                InputStream is = null;
                try {
                    //创建一个url对象
                    URL resurl = new URL(url);
                    //设置超时时间
                    HttpURLConnection urlConn = (HttpURLConnection) resurl.openConnection();
                    urlConn.setConnectTimeout(5000);
                    urlConn.setReadTimeout(5000);
                    urlConn.setUseCaches(true);
                    urlConn.connect();
                    int code = urlConn.getResponseCode();
                    if (code != 200) {
                        if (errorImgId > 0) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    setImage(imageID, true, errorImgId, null);
                                }
                            });
                        } else {
                            imageViewMap.remove(imageID);
                        }
                        return;
                    }

                    //打开URL对应的资源输入流
                    is = urlConn.getInputStream();


                    String filePath = applicationContext.getExternalCacheDir() + File.separator + imageID;


                    /*开始解析图片*/
                    Bitmap bitmap;
                    ImageView tempImageView = imageViewMap.get(imageID);
                    if (urlConn.getContentLength() > 300000) {//大于300k的先存文件
                        writeToFile(is, filePath);
                        bitmap = loadImage(imageID, tempImageView == null? 2:tempImageView.getMeasuredWidth());
                    } else {//其他直接获取bitmap并存储
                        byte[] byteArray = getBytesInputStream(is);

                        bitmap = loadImage(byteArray, tempImageView == null? 2:tempImageView.getMeasuredWidth());

                        writeToFile(byteArray, filePath);
                    }

                    /*解析图片完成*/

                    //关闭输入流
                    is.close();



                    /*开始缓存及显示图片*/
                    WeakReference<Bitmap> weakReference = new WeakReference<>(bitmap);
                    mImageCache.put(imageID, weakReference);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mImageCache.get(imageID) != null) {
                                setImage(imageID, false, errorImgId, mImageCache.get(imageID).get());
                            } else {
                                if (errorImgId > 0) {
                                    setImage(imageID, true, errorImgId, null);
                                } else {
                                    imageViewMap.remove(imageID);
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();

                    if (errorImgId > 0) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                setImage(imageID, true, errorImgId, null);
                            }
                        });
                    } else {
                        imageViewMap.remove(imageID);
                    }
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    private void setImage(String imageID, boolean isError, int errorImgId, Bitmap bitmap){
        ImageView imageView = imageViewMap.remove(imageID);
        if (imageView != null) {
            if (isError) {
                if (errorImgId > 0) {
                    imageView.setImageResource(errorImgId);
                }
            } else {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    /**从缓存文件中加载图片*/
    private Bitmap loadImage(String imageID, int width){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(applicationContext.getExternalCacheDir() + File.separator + imageID, options);

        options.inSampleSize = width > 0?options.outWidth / width:2;//默认缩小一倍
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeFile(applicationContext.getExternalCacheDir() + File.separator + imageID, options);
    }

    /**从二进制数组中加载图片*/
    private Bitmap loadImage(byte[] array, int width){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(array, 0, array.length,  options);

        options.inSampleSize = width > 0?options.outWidth / width:2;//默认缩小一倍
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeByteArray(array, 0, array.length,  options);
    }

    /**
     * 获取带后缀的图片名
     * https://pics2.baidu.com/feed/d043ad4bd11373f07cfedf093f1d9bfcfaed0479.jpeg?token=de18eb3030df73681a7ee453fb698651&s=95A742B60A9168CEE4BF9D7A03009018
     * https://img-home.csdnimg.cn/images/20201231031228.jpg
     *
     * @param imageUrl 图片url
     * @return 带后缀的图片名
     */
    private String getImageName(String imageUrl) {
        if (imageUrl.contains("?")) {//带参数
            imageUrl = imageUrl.substring(0, imageUrl.indexOf("?"));
        }
        return imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
    }

    /**图片大于300k时先写入文件,防止图片很大导致oom*/
    private void writeToFile(InputStream is, String fileAbsolutePath) {
        BufferedInputStream bufferedInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {

            bufferedInputStream = new BufferedInputStream(is);
            fileOutputStream = new FileOutputStream(fileAbsolutePath);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            byte[] buff = new byte[512];
            int len;
            while ((len = bufferedInputStream.read(buff)) != -1) {
                bufferedOutputStream.write(buff, 0, len);
            }
        } catch (IOException e){
           e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**小图时加载到内存并保存*/
    private void writeToFile(byte[] data, String fileAbsolutePath) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileAbsolutePath);
            outputStream.write(data, 0, data.length);
            outputStream.flush();

            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    如果图片比较大可能会导致oom,因此先保存,从文件中读取
    private byte[] getBytesInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[512];
        int len;
        while ((len = is.read(buff)) != -1) {
            arrayOutputStream.write(buff, 0, len);
        }
        is.close();
        arrayOutputStream.close();
        return arrayOutputStream.toByteArray();
    }

    /**app内存不够用时清空内存缓存*/
    public void onLowMemory(){
        mImageCache.evictAll();
    }
}

2.使用方法:

布局中添加ImageView:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:ignore="ContentDescription" />
</androidx.constraintlayout.widget.ConstraintLayout>

代码中调用:

package com.david.basemodule

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.david.basemodule.http.LruImageLoader
import com.david.basemodule.http.MyRetrofitHelper
import com.david.basemodule.http.method.main.IMainInterface
import com.david.basemodule.http.response.MyRetrofitResponse
import com.david.basemodule.http.response.RetrofitBaseSubscriber
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    val TAG = "main"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        test.setOnClickListener { request() }
        LruImageLoader.getInstance().init(application)
    }


    private fun request(){
        //        LruImageLoader.getInstance().loadCacheImage("http://192.168.1.110:8081/bigImg.NEF",image_view, R.mipmap.ic_launcher, R.mipmap.ic_launcher_round)
        LruImageLoader.getInstance().loadCacheImage("https://img-home.csdnimg.cn/images/20201231031228.jpg",
            image_view, R.mipmap.ic_launcher, R.mipmap.ic_launcher_round)


        val interFace = MyRetrofitHelper.getInstance().retrofit.create(IMainInterface::class.java)

        val map = HashMap<String, Any>()
        map["token"] = "testtoken"
        val json = JSONObject()
        json["innerData"] = "testInnerData"

        map["inner"] = json
        val flowable = interFace.getMainData(map)

        MyRetrofitHelper.getInstance().request(object : RetrofitBaseSubscriber() {
            override fun onSuccess(response: MyRetrofitResponse?) {
                Log.e("retrofit", JSON.toJSONString(response))
            }

            override fun onFail(throwable: Throwable?) {
                throwable?.printStackTrace()
            }
        }, flowable)

    }

    override fun onLowMemory() {
        super.onLowMemory()
        LruImageLoader.getInstance().onLowMemory()
    }
}







注:使用BitmapFactory加载图片时尽量用RGB_565格式的,以及根据控件大小加载图片。对于图片内存占用见下面几张图:
当把图片处理代码注释时(处理的代码为注释的四行):

图片占用图片内存如图(309103):

当使用把注释放开之后内存图片占用如图(9847):

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值