Save / Load image to/from local storage

早过忘川 提交于 2019-12-13 18:30:27

问题


First of all, my permissions:

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

My methods to save and get the image:

private void saveIamgeToLocalStore(Bitmap finalBitmap) { 
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/temp");    
        myDir.mkdirs(); 
        String fname = "Profile_Image.png";
        File file = new File (myDir, fname);
        if (file.exists()) file.delete(); 
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close(); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadImageFromLocalStore(String imageURI) { 
        try {
            Uri uri = Uri.parse(Environment.getExternalStorageDirectory().toString() + imageURI); 
            Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri));
            profileImage.setImageBitmap(bitmap);
            profileImage.setTag("Other");
            select_image_button.setText(R.string.button_remove_profile_picture); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace();
        } 
    }

Usage:

saveIamgeToLocalStore(BitmapFactory.decodeFile(picturePath));
loadImageFromLocalStore("/temp/Profile_Image.png");

I'm getting a

java.io.FileNotFoundException: No content provider: ... 

warning.

What am I missing?

PS: The image gets saved in /mnt/sdcard/temp/ . The warning appears when loading the image.


回答1:


Is your file getting saved? In case yes, may be the mediascanner is not triggered before you do a read of the file. Since the mediascanner is not triggered, so content provider wont have the entry for your file (your file is not indexed).In case your file is getting saved with "saveIamgeToLocalStore", then trigger mediascanner from code once like this:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
                        .parse("file://"
                                + Environment.getExternalStorageDirectory())));

and then do a read on the file. It should work.




回答2:


You need to write file existing check. Then it'll be easier to find problem. Short example

File test = new File (URI)
if ( test.exists() )
{
    // do your computation
} else 
{
    // find problem in file path
}


来源:https://stackoverflow.com/questions/18073260/save-load-image-to-from-local-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!