zhangzengfei
2022-01-10 4496b59ab27d569df1da7ef634e02273b3a9618a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.basic.security.utils;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.widget.ImageView;
 
/**
 * Created by hasee on 2018/7/17.
 */
 
public class ImageUtils {
 
    public static LruCache<String, Bitmap> imgCache;
 
    private static void init() {
        int maxCache = (int) (Runtime.getRuntime().maxMemory() / 1024);
        imgCache = new LruCache<String, Bitmap>(maxCache / 8) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
 
            @Override
            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                oldValue.recycle();
                oldValue = null;
                super.entryRemoved(evicted, key, oldValue, newValue);
            }
        };
    }
 
    public static Bitmap setScaleBitmap(String path, ImageView imageView) {
        if (imgCache == null) {
            init();
        }
        Bitmap bitmap = imgCache.get(path);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return bitmap;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;
 
        int viewWidth = imageView.getWidth();
        int viewHeight = imageView.getHeight();
 
        int scale = 1;
        if (viewWidth == 0 || viewHeight == 0) {
            imageView.setImageBitmap(BitmapFactory.decodeFile(path));
            return null;
        }
        int scaleWidth = imageWidth / viewWidth;
        int scaleHeight = imageHeight / viewHeight;
        if (scaleWidth >= scaleHeight && scaleWidth > 1) {
            scale = scaleWidth;
        } else if (scaleWidth < scaleHeight && scaleHeight > 1) {
            scale = scaleHeight;
        }
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeFile(path, options);
        imageView.setImageBitmap(bitmap);
        imgCache.put(path, bitmap);
        return bitmap;
    }
}