lmw
2023-06-13 4b7d8d9a038f6522df46d0f14fa07eb940a1b34d
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.kuanzhai.driver.utils;
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class BitmapUtil {
    
    
    public static String bitmap2File(Context context, Bitmap bitmap, String name) {
        File file = new File(context.getExternalCacheDir() + "/image/");
        if (!file.exists()) {
            file.mkdirs();
        }
        File f = new File(file, name + ".jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            return "";
        }
        return f.getAbsolutePath();
    }
 
    /**
     * 图片按比例大小压缩方法
     *
     * @param srcPath (根据路径获取图片并压缩)
     * @return
     */
    public static Bitmap getimage(String srcPath, float width, float height) {
 
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        // 此时返回bm为空
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
        // 这里设置高度为800f
        float hh = height;
        // 这里设置宽度为480f
        float ww = width;
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        // be=1表示不缩放
        int be = 1;
        // 如果宽度大的话根据宽度固定大小缩放
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
            // 如果高度高的话根据宽度固定大小缩放
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        // 设置缩放比例
        newOpts.inSampleSize = be;
        // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        // 压缩好比例大小后再进行质量压缩
//        return compressImage(bitmap);
 
        //不进行质量压缩
        return bitmap;
    }
 
    public static String getShareIconPath(Context context, int resourse) {
        File file = new File(context.getExternalCacheDir() + "/image/share_icon.jpg");
        if (file.exists()) {
            return file.getAbsolutePath();
        }
        //保存图片
        Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(),resourse);
 
        String share_icon = bitmap2File(context,thumbBmp, "share_icon");
        return share_icon;
    }
}