简体   繁体   中英

Saving an ImageView to Gallery - Code isn't working

This is my first question here. I've searched for my doubt. I found similar questions but i haven't exactly got my answer. So please forgive me if i have done something wrong. I'm trying to save an image from an ImageView in my app to a folder in my sdcard. Here's the code :-

public void save(View view) {
    myImage.setDrawingCacheEnabled(true);
    Bitmap imgV = myImage.getDrawingCache();
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/AVP_saved");
    String fname="Image.png";
    File file = new File(myDir, fname);
        try {
               FileOutputStream out = new FileOutputStream(file);
               imgV.compress(Bitmap.CompressFormat.PNG, 90, out);
               out.flush();
               out.close();
               Toast.makeText(this, "Image Downloaded", 7000).show();

        } catch (Exception e) {
               e.printStackTrace();
               Toast.makeText(this, e.getMessage(), 8000).show();
        }
    }

'save' method is the method assigned to a button. 'myImage' is the ImageView found by its id. I have already set the permissions in the manifest. The thing is, the image dosen't get saved and it says that the path dosen't exist. When I myself create the folder "AVP_saved", then the image gets saved. What do i have to edit in this code such that the app creates the folder by itself when i click the button?

Thanks for your time!

Add this code after File myDir = new File(root + "/AVP_saved");

if(!myDir.exists()) {
  mydir.mkdir(); //you can else call mkdirs() if you have to create a complete directory hierarchy
}

It seems that in Java, it's not possible to create a directory hierarchy by creating just a file in it. With this, you'll create your directory only if it doesn't exist (be careful, if the directory exists but it's a file, it will launch an exception maybe, so you can look for myDir.isDirectory() too).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM