声明
在开发时,我使用了Bmob云数据库想要来存储我的图片,但是由于它直接存储图片(file类型),需要用到域名,没有去配置,所以我决定就只是保存图片的真实地址,在网上试过很多的办法,大部分都是由于android版本的原因,不适配,反正我是没有找到自己的原因。
一.Uri->Path
我通过使用Glide图像库来处理图片,但这部分代码不是重点
//打开相册,调用图片
private void setupImagePicker() {
mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
// 处理选择的图片,例如将其显示在 ImageView 中
if (uri != null) {
ImageView imageView = findViewById(R.id.icon_avatar);
Glide.with(MainActivity.this)
.load(uri)
.apply(RequestOptions.circleCropTransform())
.into(imageView);
imageView.setImageURI(uri);
Log.d("TAG", "uri: " + uri);
String realPath = uri.getPath();
Log.d(TAG, "realPath: "+realPath);
if(realPath!=null)
{
Log.d("TAG", "RealPath: " + realPath);
// Now you can use 'realPath' to upload the image to Bmob
Bundle extras = getIntent().getExtras();
/*String userEmail = extras.getString("userEmail");
Log.d("TAG", "userEmail: " + userEmail);*/
String userEmail = ""; // 设置默认邮箱地址
uploadImagePathToBmob(realPath,userEmail);
// getAvatar(userEmail);
}
else Log.d(TAG, "onActivityResult: 错了");
}
}
});
}
下面的才是重点,直接通过getPath函数获取uri的相对地址(最开始压根没想到)
String realPath = uri.getPath();
经过以下对比便可以发现
uploadImagePathToBmob()这个函数是我用来存储图片的相对路径的(用的邮箱作为唯一字段)
二.Path->Uri
通过还原,找到了原来的uri(实际情况得根据自己的)
public static String convertPathToContentUri(String path) {
// 将路径中的':'替换为'%3A',以匹配URI编码
String encodedPath = path.replace(":", "%3A");
// 构建完整的content URI字符串
// 注意:这里的authority需要根据实际情况替换为正确的值
String authority = "com.android.providers.media.documents";
String contentUri = "content://" + authority + encodedPath;
return contentUri;
}
函数处理之后得到path,但是现在仍是String类型的
Uri imageUri = Uri.parse(path);
在这之后再使用Glide图像库便可以做到获取图像了
弊端
这种做法肯定是不合理的,存储的uri只能作用于uri调用在自己的本机上,毕竟路径不会变嘛,唯一的好处就是不用存储file,而且比较简单,只能过渡一下。
更多的可以去参考以下的: