简体   繁体   English

将ImageView保存到图库 - 代码无效

[英]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. 我正在尝试将图像从我的应用程序中的ImageView保存到我的SD卡中的文件夹中。 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. 'save'方法是分配给按钮的方法。 'myImage' is the ImageView found by its id. 'myImage'是由其id找到的ImageView。 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. 当我自己创建文件夹“AVP_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"); File myDir = new File(root + "/AVP_saved");之后添加此代码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. 似乎在Java中,通过仅在其中创建文件来创建目录层次结构是不可能的。 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). 有了这个,只有当目录不存在时才会创建你的目录(小心,如​​果目录存在但它是一个文件,它可能会启动一个异常,所以你也可以查找myDir.isDirectory())。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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