繁体   English   中英

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

[英]Saving an ImageView to Gallery - Code isn't working

这是我的第一个问题。 我搜索了我的怀疑。 我发现了类似的问题,但我没有得到答案。 如果我做错了,请原谅我。 我正在尝试将图像从我的应用程序中的ImageView保存到我的SD卡中的文件夹中。 这是代码: -

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'方法是分配给按钮的方法。 'myImage'是由其id找到的ImageView。 我已经在清单中设置了权限。 问题是,图像不会被保存,它表示路径不存在。 当我自己创建文件夹“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
}

似乎在Java中,通过仅在其中创建文件来创建目录层次结构是不可能的。 有了这个,只有当目录不存在时才会创建你的目录(小心,如​​果目录存在但它是一个文件,它可能会启动一个异常,所以你也可以查找myDir.isDirectory())。

暂无
暂无

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

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