我的应用程序可以从库中选择照片。我想要从这个选择中获得文件路径。
这是创建选择照片意图的代码:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO);
这是从URI获取文件路径的代码:
Cursor cursor = null;
String path = null;
try {
String[] projection = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
cursor.moveToFirst();
path = cursor.getString(columnIndex);
} finally {
if (cursor != null) {
cursor.close();
}
}
return path;
在昨天更新Google相册应用之前,一切都运转良好。
现在解析URI后path
为空。
URI与此类似:content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL
我还试图用Intent.ACTION_GET_CONTENT动作创建意图 - 没有运气。
答案 0 :(得分:46)
以下代码也适用于我在最新的Google相册上获取内容URI。 我试过的是写入临时文件并返回临时图像URI,如果它在内容URI中具有权限。
您可以尝试相同:
public static String getImageUrlWithAuthority(Context context, Uri uri) {
InputStream is = null;
if (uri.getAuthority() != null) {
try {
is = context.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(is);
return writeToTempImageAndGetPathUri(context, bmp).toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
答案 1 :(得分:6)
这肯定是一种解决方法,但您可以提取真正的内容URI,因为某些原因显然已嵌入其中:content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209
我能够使用authority=media and path=external/images/media/xxx
创建新的URI,内容解析器返回了一个真实的网址。
示例代码:
String unusablePath = contentUri.getPath();
int startIndex = unusablePath.indexOf("external/");
int endIndex = unusablePath.indexOf("/ACTUAL");
String embeddedPath = unusablePath.substring(startIndex, endIndex);
Uri.Builder builder = contentUri.buildUpon();
builder.path(embeddedPath);
builder.authority("media");
Uri newUri = builder.build();
答案 2 :(得分:0)
我知道这个问题有点老了,但我仍然按照以下步骤从图库中获取图像并使用它。下面是相同的扩展功能。
fun Uri.toBitmap(context: Context?): Bitmap {
return MediaStore.Images.Media.getBitmap(context?.contentResolver, this)
}
以上下文作为参数来获取从onActivityResult(requestCode:Int,resultCode:Int,intent:Intent?)接收到的contentResolver和Uri。
要使用,只需执行以下操作:
intent?.data.toBitmap(context)
其中intent?.data
是从onActivityResult()收到的Uri。