如何将图片仅保存在我的应用程序的特定文件夹中?

时间:2019-08-26 15:32:19

标签: android storage

问题是我的应用程序将图片保存了两次;一个在相机文件夹中,另一个在我指定的文件夹中。但是当我在另一台设备上测试该应用程序时,却没有发生!

//lunch the camera and make a file to save the image in and pass it with the camera intent
    public void lunchCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.ziad.sayit",
                        photoFile);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "SayIt_" + timeStamp + "_";
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = imageFile.getAbsolutePath();
        return imageFile;
    }

所以,我想要一个解决方案,我也想将图片保存在我的应用程序的文件夹中内部 图片目录。.谢谢

2 个答案:

答案 0 :(得分:2)

除了不使用ACTION_IMAGE_CAPTURE之外,没有其他解决方案。

ACTION_IMAGE_CAPTURE将拍照委托给任意第三方相机应用程序。这些设备中预装了数十种(如果不是数百种)。有数百种可从Play商店和其他地方下载。他们对Intent动作的反应取决于他们。 理想情况下,他们只会将图像存储在EXTRA_OUTPUT指定的位置。但是,不要求它们具有这种行为。某些相机应用会将图像存储两次,一次存储在其正常位置,一次存储在EXTRA_OUTPUT中。有些人会完全忽略EXTRA_OUTPUT

如果这与您有关,请不要使用ACTION_IMAGE_CAPTURE。使用CameraX,Fotoappart,CameraKit-Android等库在您自己的应用程序中拍照。

答案 1 :(得分:0)

从OnActivityResult调用以下方法。

private void saveImage(Bitmap  image, String fileName) {

    File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
    if (!direct.exists()) {
        File directory = new File("/sdcard/DirName/");
        directory.mkdirs();
    }

    File file = new File(new File("/sdcard/DirName/"), fileName);
    if (file.exists()) {
        file.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}