我现在正在开发 ImageCompressor 应用程序。
我需要delete
and write
(更新)图像文件。在内部存储中工作正常,但 **SD 卡无法让我访问删除和写入文件。
我的应用程序如何能够做到write
and delete
对sd卡的操作(移动存储)?
我已经在没有这个的情况下完成了整个项目,所以我必须找到一种方法。
Update:
我已经在研究和讨论这个问题了。并明白我必须使用storage access framework
但我是 SAF 的新手。
我用了一个library压缩需要的照片文件不是 Uri。为此我做Uri -> File
并使用Intent.ACTION_OPEN_DOCUMENT
并从可移动存储中选取图像。
但对于可移动存储,我无法从 uri 找到图像真实路径。
我不知道这是正确的方法还是错误的方法。如果有什么办法在 SAF 中我可以使用 uri 压缩我的图像, 让我知道。或者如何从uri获取图像真实路径可移动存储照片。
更新代码SAF:
// ----------- Intent -------------
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
// ------------ On Activity Result --------------
Uri uri = data.getData();
try {
ParcelFileDescriptor fileDescriptor = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fos = new FileOutputStream(fileDescriptor.getFileDescriptor());
FileInputStream fis = new FileInputStream(getImageFilePath(uri));
FileChannel source = fis.getChannel();
FileChannel destination = fos.getChannel();
destination.transferFrom(source, 0, source.size());
fis.close();
fos.close();
fileDescriptor.close();
Toast.makeText(this, "File save successfully.", Toast.LENGTH_SHORT).show();
}
Uri 到文件路径,我完成了从媒体应用程序(例如图库、照片)中选择图像的操作,但是从 SD 卡中选择的内容将代替MediaStore.Images.Media.DATA
我不知道。代码:
private File getImageFilePath(Uri uri) throws IOException {
String image_id = null, imagePath = null;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
}
cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
File file = new File(imagePath);
return new Compressor(this).setQuality(50).compressToFile(file);
}