如何在android中获取uri的图像资源

use*_*874 92 android uri

我需要打开一个意图来查看图像,如下所示:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("@drawable/sample_1.jpg");
intent.setData(uri);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

问题是这Uri uri = Uri.parse("@drawable/sample_1.jpg");是不正确的.

Axa*_*dax 134

格式为:

"android.resource://[package]/[res id]"

[package]是你的包名

[res id]是资源ID的,例如R.drawable.sample_1

将它拼接在一起,使用

Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.sample_1);

  • 当我尝试将图像作为电子邮件附件发送时,它正在发送文件,但没有.jpg扩展名.因此图像在收件人pc中无效. (4认同)
  • Uri路径= Uri.parse(“ android.resource://net.londatiga.android.twitpic/” + R.drawable.icon); 字符串mpath = path.toString(); 我在执行此操作时未收到此类文件或目录错误 (3认同)

Uli*_*Uli 61

这是一个干净的解决方案,它android.net.Uri通过其Builder模式充分利用类,避免重复组合和分解URI字符串,而不依赖于硬编码字符串或关于URI语法的临时想法.

Resources resources = context.getResources();
Uri uri = new Uri.Builder()
    .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
    .authority(resources.getResourcePackageName(resourceId))
    .appendPath(resources.getResourceTypeName(resourceId))
    .appendPath(resources.getResourceEntryName(resourceId))
    .build();
Run Code Online (Sandbox Code Playgroud)


xna*_*gyg 54

public static Uri resourceToUri(Context context, int resID) {
        return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                context.getResources().getResourcePackageName(resID) + '/' +
                context.getResources().getResourceTypeName(resID) + '/' +
                context.getResources().getResourceEntryName(resID) );
    }
Run Code Online (Sandbox Code Playgroud)


san*_*one 8

对于那些有错误的人,您可能输入了错误的包名.只需使用此方法.

public static Uri resIdToUri(Context context, int resId) {
    return Uri.parse(Consts.ANDROID_RESOURCE + context.getPackageName()
                     + Consts.FORESLASH + resId);
}
Run Code Online (Sandbox Code Playgroud)

哪里

public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FORESLASH = "/";
Run Code Online (Sandbox Code Playgroud)

  • 你是不是真的做了一个长剑? (10认同)

Ser*_*gio 5

基于上面的答案,我想分享一个关于如何为项目中的任何资源获取有效 Uri 的 kotlin 示例。我认为这是最好的解决方案,因为您不必在代码中输入任何字符串,也不必冒输入错误的风险。

    val resourceId = R.raw.scannerbeep // r.mipmap.yourmipmap; R.drawable.yourdrawable
    val uriBeepSound = Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(resources.getResourcePackageName(resourceId))
        .appendPath(resources.getResourceTypeName(resourceId))
        .appendPath(resources.getResourceEntryName(resourceId))
        .build()
Run Code Online (Sandbox Code Playgroud)