Android开发:权限处理、文件存储、图片处理常用代码

本文整理Android开发中高频使用的权限申请、文件存储工具类、图片压缩/旋转/保存工具代码,可直接复制使用。

一、权限处理代码

外部存储写入权限为例,适配Android 6.0+动态权限。

1. 权限申请方法

1
2
3
4
5
6
7
private void requestWritePermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
        }
    }
}

2. 权限结果回调

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Override
public void onRequestPermissionsResult(
        int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == Permission.REQUEST_CODE) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                Log.e("Permission","授权失败!");
                // 授权失败,退出应用
                this.finish();
                return;
            }
        }
    }
}

3. 在 onCreate 中调用

1
2
3
4
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWritePermission();
}

二、文件存储工具类(FileUtils)

包含文件创建、删除、复制、Bitmap 转字节、MD5、数据库备份等常用方法。

  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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileUtils {

    private String TAG = FileUtils.class.getSimpleName();
    public static String SDPATH = Environment.getExternalStorageDirectory() + "/.photocomb/";
    public static String DBName = "privalbum.db";
    public static String DBPATH = "/data/data/com.cm.photocomb/databases/" + DBName;

    /**
     * 操作成功返回值
     */
    public static final int SUCCESS = 0;

    /**
     * 操作失败返回值
     */
    public static final int FAILED = -1;

    private static final int BUF_SIZE = 32 * 1024; // 32KB

    /**
     * 获取录音文件路径
     */
    public static String getFileName() {
        String path = SDPATH;
        File file = new File(path);
        file.mkdirs();
        path += System.currentTimeMillis();
        return path;
    }

    /**
     * Bitmap转字节数组
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * bytes转十六进制字符串
     */
    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * 十六进制字符串转byte数组
     */
    public static byte[] hexStr2Bytes(String src) {
        int m = 0, n = 0;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
        }
        return ret;
    }

    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * 计算文件MD5值
     */
    public static String md5sum(String filename) {
        if (TextUtils.isEmpty(filename)) {
            return null;
        }
        InputStream fis;
        byte[] buffer = new byte[1024];
        int numRead = 0;
        MessageDigest md5;
        try {
            fis = new FileInputStream(filename);
            md5 = MessageDigest.getInstance("MD5");
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            fis.close();
            return toHexString(md5.digest());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 保存Bitmap到文件
     */
    public static void saveBitmap(Bitmap bm, String picName) {
        Log.e("", "保存图片");
        try {
            File f = new File(picName);
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            if (bm != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            }
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean saveBitmap(Bitmap bitmap, File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 创建SD卡目录
     */
    public static File createSDDir(String dirName) throws IOException {
        File dir = new File(SDPATH + dirName);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir.mkdir();
        }
        return dir;
    }

    /**
     * 判断文件是否存在
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

    /**
     * 删除文件
     */
    public static void delFile(String fileName) {
        File file = new File(SDPATH + fileName);
        if (file.isFile()) {
            file.delete();
        }
    }

    /**
     * 删除目录及子文件
     */
    public static void deleteDir() {
        File dir = new File(SDPATH);
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir();
        }
        dir.delete();
    }

    public static boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            return f.exists();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 删除单个文件
     */
    public static boolean deleteFile(String sPath) {
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 删除目录及目录下所有文件
     */
    public static boolean deleteDirectory(String sPath) {
        if (TextUtils.isEmpty(sPath)) {
            return false;
        }
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                flag = deleteFile(file.getAbsolutePath());
                if (!flag) break;
            } else {
                flag = deleteDirectory(file.getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        return dirFile.delete();
    }

    /**
     * 文件转字节数组
     */
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字节数组保存为文件
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 备份数据库
     */
    public static void backupDB(Context mContext) {
        try {
            File backup = new File(SDPATH + DBName);
            File dbFile = mContext.getDatabasePath(DBPATH);
            backup.createNewFile();
            fileCopy(dbFile, backup);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件复制
     */
    public static void fileCopy(File dbFile, File backup) throws IOException {
        FileChannel inChannel = new FileInputStream(dbFile).getChannel();
        FileChannel outChannel = new FileOutputStream(backup).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }

    /**
     * assets文件复制到本地
     */
    public static int assetToFile(Context context, String assetName, String path) {
        return assetToFile(context, assetName, new File(path));
    }

    public static int assetToFile(Context context, String assetName, File file) {
        InputStream is = null;
        try {
            is = context.getAssets().open(assetName);
            return streamToFile(file, is, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return FAILED;
    }

    /**
     * 流写入文件
     */
    public static int streamToFile(String path, InputStream is, boolean isAppend) {
        return streamToFile(new File(path), is, isAppend);
    }

    public static int streamToFile(File file, InputStream is, boolean isAppend) {
        checkParentPath(file);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, isAppend);
            byte[] buf = new byte[BUF_SIZE];
            int readSize;
            while ((readSize = is.read(buf)) != -1)
                fos.write(buf, 0, readSize);
            fos.flush();
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return FAILED;
    }

    /**
     * 检查并创建父目录
     */
    public static void checkParentPath(String path) {
        checkParentPath(new File(path));
    }

    public static void checkParentPath(File file) {
        File parent = file.getParentFile();
        if (parent != null && !parent.isDirectory())
            createDir(parent);
    }

    /**
     * 创建文件夹
     */
    public static int createDir(String path) {
        return createDir(new File(path));
    }

    public static int createDir(File file) {
        if (file.exists()) {
            if (file.isDirectory())
                return SUCCESS;
            file.delete();
        }
        if (file.mkdirs())
            return SUCCESS;
        return FAILED;
    }
}

三、图片处理工具类(XUtils)

包含图片压缩、旋转纠正、获取缩略图、Bitmap 保存、网络判断、内存获取等。

  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
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class XUtils {

    /**
     * 判断文件是否存在
     */
    public static Boolean fileExists(String vPath) {
        if (null == vPath || "".equals(vPath)) {
            return false;
        }
        try {
            File file = new File(vPath);
            return file.exists();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 计算图片缩放比例
     */
    public static int calculateInSampleSize(Options options, int maxWidth, int maxHeight) {
        int inSampleSize = 1;
        final int height = options.outHeight;
        final int width = options.outWidth;
        int minhw = Math.min(height, width);

        if (minhw >= maxWidth) {
            inSampleSize = Math.round((float) width / (float) maxWidth);
            while (minhw / inSampleSize > maxWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 获取图片缩略图(带旋转纠正)
     */
    public static Bitmap getThumbImg(String vPath, int vWidth, int vHeight) {
        if (null == vPath || vPath.trim().equals("")) {
            return null;
        }
        File file = new File(vPath);
        if (!file.exists()) {
            return null;
        }
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(vPath, options);
        if (options.outWidth <= 0 || options.outHeight <= 0) {
            return null;
        }
        options.inSampleSize = calculateInSampleSize(options, vWidth, vHeight);
        options.inJustDecodeBounds = false;
        Bitmap thumbImgNow = null;
        try {
            thumbImgNow = BitmapFactory.decodeFile(vPath, options);
        } catch (OutOfMemoryError e) {
            return null;
        }
        int degree = readPictureDegree(vPath);
        if (degree != 0) {
            thumbImgNow = rotateImage(degree, thumbImgNow);
        }
        return thumbImgNow;
    }

    /**
     * 旋转图片
     */
    public static Bitmap rotateImage(int angle, Bitmap bitmap) {
        if (null == bitmap) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            return bitmap;
        }
    }

    /**
     * 读取图片旋转角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 字节数组保存到文件
     */
    public static Boolean saveByteToFile(byte[] vData, String vFilePath) {
        if (null == vData || TextUtils.isEmpty(vFilePath)) {
            return false;
        }
        File tFile = new File(vFilePath);
        try {
            FileOutputStream fos = new FileOutputStream(tFile);
            fos.write(vData);
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从文件读取字节数组
     */
    public static byte[] loadByteFromFile(String vFilePath, int vLen) {
        if (TextUtils.isEmpty(vFilePath) || vLen < 1) {
            return null;
        }
        File tFile = new File(vFilePath);
        byte[] tByte = new byte[vLen];
        try (FileInputStream fin = new FileInputStream(tFile)) {
            int r = fin.read(tByte);
            if (r != vLen) {
                throw new IOException("Can't read all");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tByte;
    }

    /**
     * 保存Bitmap到本地
     */
    public static Boolean saveBitmap(Bitmap vBmp, String vPath) {
        if (null == vBmp || vBmp.isRecycled() || TextUtils.isEmpty(vPath)) {
            return false;
        }
        File file = new File(vPath).getParentFile();
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileOutputStream fout = new FileOutputStream(vPath);
            BufferedOutputStream bos = new BufferedOutputStream(fout);
            vBmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断网络是否连接
     */
    public static Boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            return mNetworkInfo != null && mNetworkInfo.isAvailable();
        }
        return false;
    }

    /**
     * 获取可用内存
     */
    public static long getmem_UNUSED(Context mContext) {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem / 1024;
    }

    /**
     * Bitmap拷贝(防内存溢出)
     */
    public static Bitmap bmpcopy(Bitmap srcBmp) {
        Bitmap destBmp = null;
        try {
            File file = new File("/mnt/sdcard/tempbmp/tmp.txt");
            file.getParentFile().mkdirs();
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            int width = srcBmp.getWidth();
            int height = srcBmp.getHeight();
            FileChannel channel = randomAccessFile.getChannel();
            MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, (long) width * height * 4);
            srcBmp.copyPixelsToBuffer(map);
            srcBmp.recycle();
            destBmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
            map.position(0);
            destBmp.copyPixelsFromBuffer(map);
            channel.close();
            randomAccessFile.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return destBmp;
    }

    /**
     * 等比缩放图片(按最小边缩放)
     */
    public static Bitmap getScaledBitmap(String vPath, int vMinWidth) {
        if (null == vPath || vPath.trim().equals("")) {
            return null;
        }
        File file = new File(vPath);
        if (!file.exists()) {
            return null;
        }
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(vPath, options);
        if (options.outWidth <= 0 || options.outHeight <= 0) {
            return null;
        }
        int tMinWidth = Math.min(options.outWidth, options.outHeight);
        options.inSampleSize = Math.max(1, tMinWidth / vMinWidth);
        options.inJustDecodeBounds = false;
        Bitmap thumbImgNow = null;
        try {
            thumbImgNow = BitmapFactory.decodeFile(vPath, options);
        } catch (OutOfMemoryError e) {
            return null;
        }
        int degree = readPictureDegree(vPath);
        if (degree != 0) {
            thumbImgNow = rotateImage(degree, thumbImgNow);
        }
        int wid = thumbImgNow.getWidth();
        int hgt = thumbImgNow.getHeight();
        tMinWidth = Math.min(wid, hgt);
        if (tMinWidth > vMinWidth) {
            float ratio = ((float) vMinWidth) / tMinWidth;
            Matrix matrix = new Matrix();
            matrix.postScale(ratio, ratio);
            thumbImgNow = Bitmap.createBitmap(thumbImgNow, 0, 0, wid, hgt, matrix, true);
        }
        return thumbImgNow;
    }
}

说明

  • 代码适配Android 6.0+,存储权限需动态申请。
  • 文件存储路径、包名可根据项目自行修改。
  • 图片处理已做OOM 防护与旋转自动纠正。

使用方法

  1. 新建文本文件
  2. 粘贴上面全部内容
  3. 重命名为:android-dev-code.md
  4. 直接上传/使用即可
汇聚多领域优质学习资料、专业知识科普、实用干货技巧与前沿行业动态,持续分享各类学习方法、经验总结与成长干货。致力于打造全面、便捷、高效的一站式综合学习平台,助力每一位学习者提升知识储备、强化专业能力、实现高效学习与长期成长,在不断积累中遇见更好的自己。