gpt4 book ai didi

android - 从存储访问框架 UI 获取文件夹后保存图像

转载 作者:行者123 更新时间:2023-11-30 00:23:01 27 4
gpt4 key购买 nike

我设置了首选项,让用户使用存储访问框架为我的应用选择保存文件夹。获取 uri onActivityResult 后,我将其作为字符串保存到 SharedPreferences 并在要保存时保存图像。

我正在使用此方法成功保存图像。

public void saveImageWithDocumentFile(String uriString, String mimeType, String name) {
isImageSaved = false;
try {
Uri uri = Uri.parse(uriString);
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri);
DocumentFile file = pickedDir.createFile(mimeType, name);
OutputStream out = getContentResolver().openOutputStream(file.getUri());
isImageSaved = mBitmap.compress(CompressFormat.JPEG, 100, out);
out.close();

} catch (IOException e) {
throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();
}

如果用户删除使用 SAF 选择的文件夹,iget null DocumentFile file 并且应用程序崩溃。我的第一个问题是如何在不再次打开 SAF ui 的情况下检查文件夹是否存在。

我也想使用 ParcelFileDescriptor 通过这种方法保存相同的图像

public void saveImageWithParcelFileDescriptor(String folder, String name) {
if (mBitmap == null) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
String image = folder + File.separator + name + ".jpg";
Toast.makeText(MainActivity.this, "image " + image, Toast.LENGTH_LONG).show();

Uri uri = Uri.parse(image);
ParcelFileDescriptor pfd = null;
FileOutputStream fileOutputStream = null;
try {
pfd = getContentResolver().openFileDescriptor(uri, "w");
fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
mBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);

} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pfd != null) {
try {
pfd.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Image saved " + isImageSaved, Toast.LENGTH_SHORT).show();

}

我得到 java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/612E-B7BF%3Aname/imagePFD.jpg在线pfd = getContentResolver().openFileDescriptor(uri, "w");

这就是我调用此方法的方式,currentFolder 是我使用 intent 获得的文件夹,与第一种方法中的文件夹相同。

saveImageWithParcelFileDescriptor(currentFolder, "imagePFD");

我该如何解决这个问题,哪种方法更可取,为什么?

最佳答案

how can i check if folder exist

DocumentFile 有一个 exists() 方法。理论上,pickedDir.exists() 应该告诉您它是否存在。实际上,这取决于存储提供商。

I also want to use ParcelFileDescriptor to save same image with this method

该代码有错误:

  • 您不能使用 grantUriPermission()

    授予自己权限
  • 您不能通过串联发明任意 Uri 值,尤其是对于不属于您的提供商

How can I fix this

删除它。

which method is more preferable

第一个。

and why?

第一个可以工作,也许需要稍作调整。第二个没有机会工作。

关于android - 从存储访问框架 UI 获取文件夹后保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924864/

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