Android 保存bitmap到SD卡路径

     /**
     * 判断SD卡是否可用
     *
     * @return true : 可用<br>false : 不可用
     */
    public static boolean isSDCardEnable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }


    /**
     * 获取SD卡路径
     * <p>一般是/storage/emulated/0/</p>
     *
     * @return SD卡路径
     */
    public static String getSDCardPath() {
        if (!isSDCardEnable()) return "sdcard unable!";
        return Environment.getExternalStorageDirectory().getPath() + File.separator;
    }

    public static void saveFile(Bitmap bm, String fileName, Context context) {
        String SavePath = getSDCardPath() + "shard";
        String filepath = null;
        File file = null;
        try {
            File path = new File(SavePath);
            filepath = SavePath + "/" + fileName;
            file = new File(filepath);
            if (!path.exists()) {
                path.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();

            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filepath)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
posted @ 2022-04-14 09:27  指切  阅读(125)  评论(0编辑  收藏  举报