android保存图片到本地sd卡

1,声明路径

private static final String SAVE_PIC_PATH= Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/daokoudai/saveImg";//保存到SD卡

private static final String SAVE_REAL_PATH = SAVE_PIC_PATH+ "/daokoudai/saveImg";//保存的确切位置

2,创建方法

/**保存二维码到本地sd卡
     * @param bitmap
     * @param fileName
     * @param path
     */
    public  void saveFile(Bitmap bitmap, String fileName, String path)  {
        String subForder = SAVE_REAL_PATH + path;
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            try {
                myCaptureFile.createNewFile();
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);//压缩图片
                outputStream.flush();
                outputStream.close();
                //广播相册更新图片
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(myCaptureFile);
                intent.setData(uri);
                sendBroadcast(intent);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Toast.maketext(this,"图片收藏成功",Toast.LENGTH_SHORT).show();
        }else{
            Toast.maketext(this,"图片已收藏到本地",Toast.LENGTH_SHORT).show();
        }
    }

3,在需要的地方调用

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.img);
saveFile(bitmap, "img.png", "");

发布了151 篇原创文章 · 获赞 97 · 访问量 27万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览