doum
6 天以前 2b287056e2f59518888d05a1bbc7e5a55fbd84d5
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package com.doumee.lib_coremodel.util;
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
 
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
 
import timber.log.Timber;
 
public class PictureUtil {
 
    /**
     * 质量压缩方法
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        //Bitmap image = BitmapFactory.decodeFile(filePath,getBitmapOption(2));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断若是压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;// 每次都减小10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }
 
    private static BitmapFactory.Options getBitmapOption(int inSampleSize){
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }
 
    public static File saveBitmapFile(Context context,Bitmap bitmap){
        Timber.tag("Compressor").d("压缩中大小:"+bitmap.getByteCount()/1024,"");
        //Bitmap b= sharpenImageAmeliorate(bitmap);
        File file= new File(setMkdir(context), System.currentTimeMillis()+".jpg");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
 
    /**
     * 图片按比例大小压缩方法
     * @param filePath (根据Bitmap图片压缩)
     * @return
     */
    public static File compressScale(Context context,String  filePath) {
        Bitmap image = BitmapFactory.decodeFile(filePath,getBitmapOption(2));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断若是图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%,把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        Log.i("", w + "---------------" + h);
        // 如今主流手机比较可能是800*480分辨率,因此高和宽咱们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 1080f;
        float ww = 1080f;
        // 缩放比。因为是固定比例缩放,只用高或者宽其中一个数据进行计算便可
        int be = 1;// 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; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//下降图片从ARGB888到RGB565
        // 从新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return saveBitmapFile(context,compressImage(bitmap));// 压缩比如例大小后再进行质量压缩
        //return bitmap;
    }
 
    /**
     * 获取目录名称
     *
     * @param url
     * @return FileName
     */
    public static String getFileName(String url) {
        int lastIndexStart = url.lastIndexOf("/");
        if (lastIndexStart != -1) {
            return url.substring(lastIndexStart + 1, url.length());
        } else {
            return new Timestamp(System.currentTimeMillis()).toString();
        }
    }
 
    /**
     * 文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean FileIsExist(String path) {
        File file = new File(path);
 
        return file.exists();
    }
 
    /**
     * 判断SD卡是否存在
     *
     * @return boolean
     */
    public static boolean checkSDCard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * 保存文件到指定目录
     *
     * @param context
     * @return 文件保存的目录
     */
    public static String setMkdir(Context context) {
        String filePath = null;
        if (checkSDCard()) {
            filePath = Environment.getExternalStorageDirectory()
                    + File.separator + "com.wei.mymvvm" + File.separator
                    + "images";
        } else {
            filePath = context.getCacheDir().getAbsolutePath() + File.separator
                    + "com.wei.mymvvm" + File.separator + "images";
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
            Log.e("file", "目录不存在   创建目录    ");
        } else {
            Log.e("file", "目录存在");
        }
        return filePath;
    }
 
    public static String getFile(Context context){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            if (Build.VERSION.SDK_INT>=29){
                //Android10之后
                sdDir = context.getExternalFilesDir(null);
            }else {
                sdDir = Environment.getExternalStorageDirectory();// 获取SD卡根目录
            }
        } else {
            sdDir = Environment.getRootDirectory();// 获取跟目录
        }
        return sdDir.toString();
    }
 
    /**
     * 获取路径
     *
     * @return
     * @throws IOException
     */
    public static String getPath(Context context, String url) {
        String path = null;
        try {
            path = getFile(context) + File.separator
                    + "shixun.apk";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
 
    public static long getFileSize(File f) throws Exception// 取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        if (flist != null) {
            for (int i = 0; i < flist.length; i++) {
                if (flist[i].isDirectory()) {
                    size = size + getFileSize(flist[i]);
                } else {
                    size = size + flist[i].length();
                }
            }
        }
        return size;
    }
 
    /**
     * 获取文件的大小
     *
     * @param fileS
     *            文件的大小
     * @return
     */
    public static String FormetFileSize(long fileS) {// 转换文件大小
        DecimalFormat df = new DecimalFormat("0.0");// #.00
        String fileSizeString = "";
        if (fileS < 1024) {
            if (fileS < 70) {
                fileSizeString = "0B";
            } else {
                fileSizeString = df.format((double) fileS) + "B";
            }
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
 
    /**
     * 删除该目录下的指定文件
     *
     * @param filePath
     *            文件目录
     * @param fileName
     *            文件名
     * @return
     */
    public static boolean deleteFile(String filePath, String fileName) {
        if (FileIsExist(filePath + fileName)) {
            File file = new File(filePath + fileName);
 
            return file.delete();
        }
 
        return true;
    }
 
    /**
     * 删除该路径指定的文件
     *
     * @param path
     *            文件路径
     * @return
     */
    public static boolean deleteFile(String path) {
        if (FileIsExist(path)) {
            File file = new File(path);
            return file.delete();
        }
        return true;
    }
 
    /**
     * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理
     *
     * @param file
     */
 
    public static void deleteFilesByDirectory(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
 
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }
 
            for (int i = 0; i < childFiles.length; i++) {
                deleteFilesByDirectory(childFiles[i]);
            }
            file.delete();
        }
    }
}