【问题标题】:Can't save a photo to external storage using getFilesDir()无法使用 getFilesDir() 将照片保存到外部存储
【发布时间】:2015-02-20 05:12:12
【问题描述】:

我正在尝试将照片保存到外部存储并在 ImageView 中显示,但我不希望其他应用可以访问此照片。当我想创建该文件时,我尝试使用方法getFilesDir() 作为目录参数创建一个新的File,但是如果我问我是否可以写入它(以保存图像),它会返回我可以' t(更多细节见代码)。

请注意,该应用拥有android.permission.WRITE_EXTERNAL_STORAGE 权限。

public void takePhoto(View v) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = new File(getFilesDir(), "my_image.jpg");

    // Check if I can write in this path (I always get that I can't)
    if (file.canWrite()) {
        Toast.makeText(this, "I can write!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "I CAN'T WRITE!", Toast.LENGTH_LONG).show();
    }

    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

    startActivityForResult(intent, IMAGE_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMAGE_REQUEST_CODE) {

        File file = new File(getFilesDir(), "my_image.jpg");

        Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);

        imageView.setImageBitmap(bitmap);
    }
}

但是,如果我使用Environment.getExternalStorageDirectory() 方法,我可以保存照片。

我想我可能误解了 File 的工作原理,但我不知道具体是什么。我没有 FC,图像只是没有显示在 ImageView 中。

【问题讨论】:

  • 你试过用openFileOutput写文件吗?这是写入私有存储的标准方式。
  • 你没有对 Intent 数据做任何事情。所以这永远行不通。 'new File()' 不会在文件系统上创建文件,而只是一个 File 对象。如果您可以使用 getExternalStorageDirectory() 来完成,请在单独的代码块中显示该代码。
  • 谢谢你们,我正在检查照片是否通过在 ImageView 中显示来“保存”,但实际上我认为并没有存储它。正如@greenapps 所建议的那样,我无法以编写代码的方式使用 getExternalStorageDirectory() 保存照片。我将使用 openFileOutput 然后 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) 来存储它(我希望它会工作)。但是,我怎样才能读取图像呢?

标签: android photos


【解决方案1】:

如果您保存到外部存储,每个人都会看到图像:

这里是External Storage

那么当你收到回调onActivityResult时你会收到图片的URI

   Uri mUriFile = data.getData() 

然后根据操作系统版本可以获取文件路径

这是一个很好的帖子Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT

【讨论】:

  • 抱歉忘记了 Uri mUriFile = data.getData();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多