关于图片保存(Android)

1.申请权限

首先需要在清单文件(AndroidMainfest.xml)中加入:


android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

 

2.保存图片到系统相册和固定文件路径

 public  void savebitmap(Bitmap bmp, Context context,String path) {
    String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + path;//图片保存路径
    File appDir = new File(storePath);
    if (!appDir.exists()) {
        boolean s = appDir.mkdirs();
        if(s){
            Toast.makeText(context.getApplicationContext(),"创建成功",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(context.getApplicationContext(),"创建文件失败",Toast.LENGTH_SHORT).show();
        }
    }
    String fileName = System.currentTimeMillis() + ".jpg";//以当前时间命名图片名
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);//保存到系统相册
        //通知系统相册更新
        Uri uri = Uri.fromFile(file);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        Toast.makeText(context.getApplicationContext(),"截图成功",Toast.LENGTH_SHORT).show();

    } catch (FileNotFoundException e) {
        Toast.makeText(context.getApplicationContext(),"文件找不到异常:"+e.getMessage(),Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    } catch (IOException e) {
        Toast.makeText(context.getApplicationContext(),"IO异常:"+e.getMessage(),Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

 注意:Android 6.0及以上版本需要动态申请权限

你可能感兴趣的:(android)