如何在内部存储中创建文件夹并保存捕获的图像

时间:2019-05-03 10:55:44

标签: android android-intent camera

我要捕获图像并将其保存到内部存储中的特定文件夹中。目前,我能够打开意图并获取捕获图像的缩略图。我不想使用外部存储,因为现在大多数用户使用其内部存储器而不是SD卡。

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null){
    startActivityForResult(intent,1);
}


  @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK){
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");

        LayoutInflater inflater = LayoutInflater.from(LeaveApplicationCreate.this);
        final View view = inflater.inflate(R.layout.item_image,attachView, false);

        ImageView img = view.findViewById(R.id.img);
        AppCompatImageView btnRemove = view.findViewById(R.id.btnRemove);
        img.setImageBitmap(imageBitmap);

        btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attachView.removeView(view);
            }
        });

        attachView.addView(view);

        File directory = new File(Environment.getExternalStorageDirectory(),"/Digimkey/Camera/");
        if (!directory.exists()) {
            directory.mkdir();
        }
        File file = new File(directory, System.currentTimeMillis()+".jpg");


        try (FileOutputStream out =new FileOutputStream(file)) {
            imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  }

2 个答案:

答案 0 :(得分:1)

首先获得写权限。

if(iPtr){
   //then do something.
}

if(cPtr){
  //then do something.
}

有两种类型的存储。 1)内部防爆“/根/..”    除非您拥有根设备,否则我们将无法访问。这条路。 2)外部ex。 “ /存储/被屏蔽/ 0”    Environment.getExternalStorageDirectory() 通过使用此路径,我们可以创建目录/文件。

答案 1 :(得分:0)

用于将Bimap保存在本地存储中的方法。将bimap图片作为参数 saveToInternalStorage(imageBitmap)

private String saveToInternalStorage(Bitmap bitmapImage){
    //set image saved path 
    File storageDir = new File(Environment.getExternalStorageDirectory()
        + "MyApp"+ "/Files");

      if (!storageDir.exists()) {
        storageDir.mkdirs();
      }
    File mypath=new File(storageDir,"bitmap_image.jpg");
    FileOutputStream fos = null;
    try {           
        fos = new FileOutputStream(mypath);
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
          e.printStackTrace();
    } finally {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    } 
    return directory.getAbsolutePath();
}

清单中所需的权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />