MediaStore.Images.Media.insertImage is returning null when trying to save the image

后端 未结 2 582
心在旅途
心在旅途 2020-12-14 09:22

I am using an custom view and in that i am using an canvas in which a user can draw anything and after that i want to save that image in sd card bt was not able to do that.

相关标签:
2条回答
  • 2020-12-14 09:44

    A bit late answer, but still...

    Not sure which is line 238, but probably the reason is here:

    String imgSaved = MediaStore.Images.Media.insertImage( getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID().toString()+".png", "drawing");

    Since the method is within a click listener getContentResolver may be returning a Resolver different from the one for the application. Either save a private reference to the content resolver, or you could try replacing getContentResolver with MainActivity.this.getContentResolver() :

    String imgSaved = MediaStore.Images.Media.insertImage( MainActivity.this.getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID().toString() + ".png", "drawing");

    Alternatively, it might be a permissioning problem. Make sure in the manifest you have:

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

    One final note, the result of insertImage is an URI, imgSaved is not the best name for that variable :)

    0 讨论(0)
  • 2020-12-14 09:58

    I had this issue in the Emulator (Android 4.4) and turns out it's due to an Android bug, where it happens when the user hasn't taken a photo on the device before (i.e. gallery is empty and hasn't been initialized.). The workaround is to initialize the photo directory manually:

    void fixMediaDir() {
        File sdcard = Environment.getExternalStorageDirectory();
        if (sdcard != null) {
            File mediaDir = new File(sdcard, "DCIM/Camera");
            if (!mediaDir.exists()) {
                mediaDir.mkdirs();
            }
        }
    }
    

    Not sure if this is fixed in later versions of Android.

    0 讨论(0)
提交回复
热议问题