我有一个onActivityResult从一个mediastore图像选择返回,我可以获得一个图像使用以下URI:
Uri selectedImage = data.getData();
将this转换为字符串会得到:
content://media/external/images/media/47
或路径给出:
/external/images/media/47
然而,我似乎找不到一种方法将其转换为绝对路径,因为我想将图像加载到位图中,而不必复制到某个地方。我知道这可以使用URI和内容解析器来完成,但这似乎在重新启动手机时中断,我猜MediaStore在重新启动之间没有保持其编号相同。
这个解决方案适用于所有情况:
在某些情况下,从URL中获取路径太难了。那你为什么需要路径?把文件复制到其他地方?你不需要路径。
public void SavePhotoUri (Uri imageuri, String Filename){
File FilePath = context.getDir(Environment.DIRECTORY_PICTURES,Context.MODE_PRIVATE);
try {
Bitmap selectedImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageuri);
String destinationImagePath = FilePath + "/" + Filename;
FileOutputStream destination = new FileOutputStream(destinationImagePath);
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, destination);
destination.close();
}
catch (Exception e) {
Log.e("error", e.toString());
}
}
我用一行代码做到这一点:
val bitmap = MediaStore.Images.Media。getBitmap (contentResolver uri)
在onActivityResult中看起来是这样的:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICKER ) {
data?.data?.let { imgUri: Uri ->
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imgUri)
}
}
}
完美地为我修复了这篇文章的代码:
public static String getRealPathImageFromUri(Uri uri) {
String fileName =null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = MyApplication.getInstance().getContentResolver().query(uri, null, null, null, null)) {
if (cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndexOrThrow(ediaStore.Images.Media.DATA));
}
} catch (IllegalArgumentException e) {
Log.e(mTag, "Get path failed", e);
}
}
return fileName;
}