首页 > 解决方案 > 为什么 MediaStore.Images.Media.insertImage 总是将图像保存在 Pictures 文件夹中?

问题描述

我想将我的图像保存在与我的应用程序名称对应的文件夹中,而不是默认的“图片”文件夹中。这是我在 onRequestPermissionsResult 中的代码:

if(requestCode == SAVE_IMAGE) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + R.string.app_name + "/";
                    File dir = new File(path);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }

                    OutputStream out;
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

                    File photoFile = new File(path, timeStamp + ".jpg");
                    photoFile.createNewFile();

                    out = new FileOutputStream(photoFile);

                    Bitmap full_image_result = full_image.copy(full_image.getConfig(), true);
                    selectedFilter.apply(full_image_result);
                    full_image_result.compress(Bitmap.CompressFormat.JPEG, 90, out);

                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),photoFile.getAbsolutePath(), photoFile.getName(), photoFile.getName());

                    out.flush();
                    out.close();

                    Toast.makeText(getApplicationContext(),R.string.savedMessage, Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), R.string.noPermissions, Toast.LENGTH_LONG).show();
            }
        }

标签: androidmediastore

解决方案


不知何故,路径是错误的,将其替换为Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictura/"现在它正在工作。我还将 insertImage 调用替换为

MediaScannerConnection.scanFile(this, new String[]{photoFile.getAbsolutePath()}, new String[]{"image/jpg"}, null);

,正如 CommonsWare 建议的那样。


推荐阅读