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

时间:2012-10-19 03:39:55

标签: 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);

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

/storage/sdcard0/Pictures/appname/testing.png: open failed: EISDIR (Is a directory)

即使我不尝试将其放在目录中并将变量路径转换为像

这样的文件
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

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

***回答 问题是,当我最初运行此代码时,它创建了一个名为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);

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

6 个答案:

答案 0 :(得分: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);   

答案 1 :(得分:3)

您的代码是正确的,只需要进行少量更改,如下所示,

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

    // First Create Directory
    File outputFile = new File(path);
    outputFile.mkdirs();

    // Now Create File
    outputFile = new File(path,"testing.png");
    FileOutputStream out = new FileOutputStream(outputFile);
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out);

另外,不要忘记在AndroidManifest.xml文件中授予WRITE_EXTERNAL_STORAGE权限。

答案 2 :(得分:2)

如果您在使用Android Emulator时遇到此错误;您需要在模拟器上启用SD卡存储。

答案 3 :(得分:2)

greater

答案 4 :(得分:0)

使用这种方式:

bitmap.compress(CompressFormat.JPEG, 100,  new FileOutputStream("/mnt/sdcard/" + new Date().getTime() + ".jpg"));`

<强> Path : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + file name

答案 5 :(得分:0)

getExternalStoragePublicDirectory现在已弃用,您应该使用

context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)