How to store image in app internal memory, after s

2019-08-29 08:34发布

In my app I am selecting an image from gallery, than I cropped that image, than store it in external storage.

But if sd-card not available than problem occurs.

So here I am asking you how to store image in application internal storage.

Here is my code for external storage.

Override
    public void onClick(View v) {
        int outputX = 400;
        int outputY = 400;
        int aspectX = 1;
        int aspectY = 1;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        selectedImageUri = getTempUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);

        startActivityForResult(intent, 2);
    }

Here is how I get URI of externel file:

private Uri getTempUri() {
        return Uri.fromFile(getTempFile());
    }

    private File getTempFile() {
        if (isSDCARDMounted()) {

            File f = new File(Environment.getExternalStorageDirectory(),
                    TEMP_PHOTO_FILE);
            try {
                f.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Toast.makeText(MainActivity.this, "file issue", Toast.LENGTH_LONG)
                        .show();
            }
            return f;
        } else {
            return null;
        }

    }

    private boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();

        if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 2) {
            path = selectedImageUri.getPath();
            imageView.setImageBitmap(BitmapFactory
                    .decodeFile(path));
        }
    }

1条回答
▲ chillily
2楼-- · 2019-08-29 08:52

You can use Context's getCacheDir() method to store your image in application cache directory. Use following code to store your image inside cache directory.

//this will create a custom directory inside cache directory
File cacheDir = new File(this.getCacheDir(), "Custom_Directory");
if (!cacheDir.exists())
    cacheDir.mkdir();

//this will give you full path of cache directory. You can use this for your file
this.getCacheDir().getAbsolutePath()
查看更多
登录 后发表回答