Как создать папку во внутреннем хранилище и сохранить захваченное изображение - PullRequest
0 голосов
/ 03 мая 2019

Я хочу захватить изображение и сохранить его в определенную папку во внутренней памяти. В настоящее время я могу открыть намерение и получить эскиз захваченного изображения. Я не хочу использовать внешнюю остановку, поскольку в настоящее время большинство пользователей используют свое внутреннее хранилище, а не 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 ]

1 голос
/ 03 мая 2019

Первое получение разрешения на запись.

File directory = new File(Environment.getExternalStorageDirectory(), dirName);
        if (!directory.exists()) {
            directory.mkdirs();
          }
        File file = new File(directory, fileName);
         if (!file.exists()) {
          file.createNewFile();
        }

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

Существует два типа хранилищ. 1) Внутренний отл. "/ Корень / .." Если у вас нет рутированного устройства, мы не можем получить доступ. этот путь. 2) Внешний отл. "/ Хранение / emuated / 0" Environment.getExternalStorageDirectory () Используя этот путь, мы можем создать каталог / файл.

0 голосов
/ 03 мая 2019

Используйте метод для сохранения вашего 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" />
...