gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:53:33 24 4
gpt4 key购买 nike

我正在尝试将图像文件写入特定目录中的公共(public)画廊文件夹,但我不断收到错误消息,提示我无法打开该文件,因为它是一个目录。

目前我有以下内容

//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);

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

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

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

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

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

***回答问题是,当我最初运行这段代码时,它创建了一个名为 testing.png 的目录,因为我在目录中创建文件之前未能创建目录。所以解决方案是先创建目录,然后像这样用单独的文件写入目录

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);

请注意,如果您犯了与我开始时相同的错误,您可能需要进入您的存储并手动删除该目录

最佳答案

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

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);

关于android - 我如何在android的外部存储库中保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com