如何在android中的外部存储库中保存图像

Bri*_*ian 5 android android-sdcard android-image

我正在尝试将图像文件写入特定目录中的公共图库文件夹,但我一直收到一个错误,我无法打开该文件,因为它是一个目录.

到目前为止我所拥有的是以下内容

//set the file path
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;

    File outputFile = new File(path,"testing.png");


    outputFile.mkdirs();

    FileOutputStream out = new FileOutputStream(outputFile);
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Run Code Online (Sandbox Code Playgroud)

其中directory是应用程序名称.因此,应用程序保存的所有照片都将进入该文件夹/目录,但我一直收到错误

/storage/sdcard0/Pictures/appname/testing.png: open failed: EISDIR (Is a directory)
Run Code Online (Sandbox Code Playgroud)

即使我不尝试将它放在一个目录中并将变量路径转换为像文件一样

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Run Code Online (Sandbox Code Playgroud)

我没有收到错误,但照片仍未显示在图库中.

***答案问题是,当我最初运行此代码时,它创建了一个名为testing.png的DIRECTORY,因为在创建目录中的文件之前我无法创建目录.因此,解决方案是首先创建目录,然后使用单独的文件写入目录

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + directory;

//directory is a static string variable defined in the class

            //make a file with the directory
    File outputDir = new File(path);

            //create dir if not there
    if (!outputDir.exists()) {
         outputDir.mkdir();

    }

            //make another file with the full path AND the image this time, resized is a static string
    File outputFile = new File(path+File.separator+resized);

    FileOutputStream out = new FileOutputStream(outputFile);
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Run Code Online (Sandbox Code Playgroud)

请注意,如果你犯了同样的错误,你可能需要进入存储并手动删除目录

sac*_*chy 11

您正在尝试写入目录而不是文件.试试这个

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;   
File outputDir= new File(path);   
outputDir.mkdirs();   
File newFile = new File(path + File.separator + "test.png");
FileOutputStream out = new FileOutputStream(newFile);   
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);   
Run Code Online (Sandbox Code Playgroud)