Den*_*mus 47 android android-intent android-gallery google-photos
我的应用程序可以从库中选择照片.我想要从这个选择中获取文件路径.
这是创建选择照片的意图的代码:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO);
Run Code Online (Sandbox Code Playgroud)
这是从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;
Run Code Online (Sandbox Code Playgroud)
在昨天更新Google相册应用之前,一切都运转良好.path解析URI后现在为null.
URI类似于: content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL
我还试图用Intent.ACTION_GET_CONTENT动作创建意图 - 没有运气.
Akh*_*hil 47
下面的代码也适用于我在最新的Google相册上获取内容URI.我试过的是写入临时文件并返回临时图像URI,如果它在内容URI中具有权限.
您可以尝试相同:
private 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
{
if (is != null)
{
is.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
private 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);
}
Run Code Online (Sandbox Code Playgroud)
这肯定是一种解决方法,但您可以提取实际内容URI,该URI显然由于某种原因而嵌入: content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209
我能够创建一个新的URI authority=media and path=external/images/media/xxx,内容解析器返回一个真实的URL.
示例代码:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17987 次 |
| 最近记录: |