0

I'm trying to save a photo to external storage and display it in a ImageView, but I don't want other apps can access this photo. I try to create a new File with the method getFilesDir() as the directory argument when I want to create that file, but if I ask if I can write to it (to save the image), it return that I can't (see the code for more details).

Note that the app has the android.permission.WRITE_EXTERNAL_STORAGE permission.

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);
    }
}

However, if I use the Environment.getExternalStorageDirectory() method, I'm able to save the photo.

I think I might be misunderstanding anything about how File works, but I don't know exactly what. I have no FC, the image just doesn't show in the ImageView.

  • Have you tried using `openFileOutput` to write the file? That's the standard way to write to private storage. – nasch Feb 19 '15 at 20:54
  • You are doing nothing with Intent data. So this can never work. 'new File()' does not make a file on the file system but only a File object. If you can do it with getExternalStorageDirectory() then please show that code in a separate code block. – greenapps Feb 19 '15 at 20:54
  • Thanks both of you, I was checking if the photo was "saved" by showing it in an ImageView, but actually I think wasn't storing it. As @greenapps has suggested, I cannot save the photo with getExternalStorageDirectory() in the way my code is written. I'm gonna use openFileOutput and then bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) to store it (I hope it'll work). But then, how can I read the image? – Diego Jerez Feb 19 '15 at 22:42

1 Answers1

0

If you save to an external storage everyone will see the image :

Here's External Storage!

Then when you receive the callback onActivityResult you will receive the URI from the image

   Uri mUriFile = data.getData() 

Then depending on the OS version you can get the file path

Here´s a good post to get it Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT

Community
  • 1
  • 1
JARP
  • 1,239
  • 12
  • 12