fileProvider不保存图像

时间:2019-05-07 20:20:21

标签: java android

fileProvider似乎没有将我的图像保存到外部存储。当我进入文件时,它创建的是目录,但不是文件。我是Android编码的新手,所以请原谅我缺乏知识。

fileprovider在savePic方法中,我最初是从android dev的拍照图片教程中获得的基本代码,但已尝试为我的应用程序对其进行修改。

ImageView theView;
static final int REQUEST_IMAGE_CAPTURE = 1;
String currentPhotoPath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_the_camera);
    dispatchTakePictureIntent();
}

private void dispatchTakePictureIntent(){
    Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePic.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePic, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        theView = findViewById(R.id.cameraReturn);
        theView.setImageBitmap(imageBitmap);
    }
}

protected void retakePic(View view){
    new AlertDialog.Builder(TheCamera.this)
            .setTitle("New Picture?")
            .setMessage("Are you sure you want to take another picture?")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dispatchTakePictureIntent();
                }
            })
            .setNegativeButton(android.R.string.no,null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}
here

    protected void savePic(View view){
        Intent save = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(save.resolveActivity(getPackageManager()) != null){
            File theImage = null;
            try {
                theImage = createImageFile();

            }catch (IOException e){
               e.printStackTrace();
            }
            if(theImage != null){
                Uri uri = FileProvider.getUriForFile(this,"com.example.mygallery.fileprovider",theImage);

                Toast.makeText(this,"File Saved",Toast.LENGTH_SHORT).show();
                Log.i("FILE-SAVE", "savePic:"+ uri );
                this.finish();
            }else {
                Toast.makeText(this,"File Save Failed!",Toast.LENGTH_SHORT).show();
            }
        }
    }


to here
private File createImageFile() throws IOException {
    String stamp = new SimpleDateFormat("ddMMyyHHmmss").format(new Date());
    String fileName = "myGal_" + stamp;
    File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    File image  = File.createTempFile(fileName,".jpg",dir);
    Log.i("what the dir", "createImageFile:" + image);
    currentPhotoPath = image.getAbsolutePath();
    Log.i("what the dir-1", "createImageFile:" + currentPhotoPath);

    return image;
}
manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mygallery">

    <uses-feature
        android:name="android.hardware.camera2"
        android:required="true" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TheCamera"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.mygallery.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
    </application>

</manifest>


file paths

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.mygallery/files/Pictures/" />
</paths>


I expect to see a file in the directory.

1 个答案:

答案 0 :(得分:1)

尝试一下

 // Dont forget to ask camera and storage run time permission from user
 // add below permission in Manifest.xml file

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.CAMERA"/>

 // add global variable
  private int CAMERA_PIC_REQUEST =100;

// call takePicture() method for getting image using camera on the button click

private void takePicture(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA_PIC_REQUEST );
}


// after capture image using camera onActivityResult() method will invoke


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent 
 data) {
    if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        // call saveFile() method for save image at specific location 
        saveFile(data.getData());
    }
}


 public void saveFile(Uri selectedImage) {
    String filePath=ImageUriUtils.getRealPathFromURI(this,selectedImage);
    //file path of captured image
    File f = new File(filePath);
    // file name
    String filename= f.getName();

    File direct = new File(Environment.getExternalStorageDirectory() + "/MyApp/");
    File file = new File(Environment.getExternalStorageDirectory() + "/MyApp/" + filename + ".png");

    if (!direct.exists()) {
        direct.mkdir();
    }

    if (!file.exists()) {
        try {
            file.createNewFile();
            FileChannel src = new FileInputStream(filePath).getChannel();
            FileChannel dst = new FileOutputStream(file).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public class ImageUriUtils {
public static String getRealPathFromURI(Context context,Uri uri) {
    String path = "";
    if (context.getContentResolver() != null) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount>0) {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            path = cursor.getString(idx);
            cursor.close();
        }
    }
    return path;
}

}