Camera Intent not saving photo

后端 未结 2 613
星月不相逢
星月不相逢 2020-12-04 22:30

I successfully have used this code snippet before, but with the file pointing to somewhere on the SD card.

final File temp = new File(getCacheDir(), \"temp.j         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 23:08

    Best solution I found is: FileProvider (needs support-library-v4)
    It uses the internal storage! https://developer.android.com/reference/android/support/v4/content/FileProvider.html

    1. Define your FileProvider in Manifest in Application element:

      
            
      
      
    2. Add camera feature to AndroidManifest.xml's root element if mandatory:

      
      
    3. Define your image paths in for example res/xml/image_path.xml:

      
      
      
      
    4. Java:

      private static final int IMAGE_REQUEST_CODE = 1;
      // your authority, must be the same as in your manifest file 
      private static final String CAPTURE_IMAGE_FILE_PROVIDER = "your.package.name.fileprovider";
      

    4.1 capture intent:

        File path = new File(activity.getFilesDir(), "your/path");
        if (!path.exists()) path.mkdirs();
        File image = new File(path, "image.jpg");
        Uri imageUri = FileProvider.getUriForFile(activity, CAPTURE_IMAGE_FILE_PROVIDER, image);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    

    4.2 onActivityResult():

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == IMAGE_REQUEST_CODE) {
                if (resultCode == Activity.RESULT_OK) {
                    File path = new File(getFilesDir(), "your/path");
                    if (!path.exists()) path.mkdirs();
                    File imageFile = new File(path, "image.jpg");
                    // use imageFile to open your image
                }
            }
            super.onActivityResult(requestCode, resultCode, intent);
        }
    

提交回复
热议问题