如何在android中获取图像资源的uri
我需要打开一个意图来查看图像,如下所示:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("@drawable/sample_1.jpg");
intent.setData(uri);
startActivity(intent);
问题是 Uri uri = Uri.parse("@drawable/sample_1.jpg");
不正确。
I need to open an intent to view an image as follows:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("@drawable/sample_1.jpg");
intent.setData(uri);
startActivity(intent);
The problem is that Uri uri = Uri.parse("@drawable/sample_1.jpg");
is incorrect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
格式为:
"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);
The format is:
"android.resource://[package]/[res id]"
[package] is your package name
[res id] is value of the resource ID, e.g. R.drawable.sample_1
to stitch it together, use
Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.sample_1);
这是一个干净的解决方案,充分利用
android.net.Uri
类通过其
Builder
模式,避免 URI 字符串的重复组合和分解,而不依赖于硬编码字符串或有关 URI 语法的临时想法。使用 Kotlin 至少更优雅:
在 Jetpack Compose 中:
Here is a clean solution which fully leverages the
android.net.Uri
class via itsBuilder
pattern, avoiding repeated composition and decomposition of the URI string, without relying on hard-coded strings or ad hoc ideas about URI syntax.Minimally more elegant with Kotlin:
In Jetpack Compose:
对于那些有错误的人,您可能输入了错误的包名称。只要用这个方法就可以了。
在哪里
For those having error, you may be entering the wrong package name. Just use this method.
Where
基于上面的答案,我想分享一个关于如何为项目中的任何资源获取有效 Uri 的 kotlin 示例。我认为这是最好的解决方案,因为您不必在代码中输入任何字符串,也不必冒输入错误的风险。
Based on the answers above I want to share a kotlin example on how to get a valid Uri for any resource in your project. I think it's the best solution because you don't have to type any strings in your code and risk typing it wrongly.
您需要图像资源的 URI,而 R.drawable.goomb 是图像资源。 Builder 函数创建您要求的 URI:
You want the URI of the image resource, and
R.drawable.goomb
is an image resource. The Builder function creates the URI that you are asking for:基于上面的 @xnagyg 答案,我做了一个方便的扩展,希望对其他人也有用,
可以像
context.resources.getRawUri(R.raw.rawid)
一样使用Based on @xnagyg answer above I've made a convenience extension which hopefully will be useful for others also,
which can be used like
context.resources.getRawUri(R.raw.rawid)
要获取 Android 应用程序中可绘制资源的内容 URI,您需要使用 android.resource 方案构造一个 URI。
To get the content URI for a drawable resource in an Android application, you need to construct a URI using the android.resource scheme.
如果可绘制对象是矢量或者您生成的图像资源包含 XML 以及所有其他 PNG 文件,您将不会获得 Uri。
https://github.com/bumptech/glide/issues/2137
You will not get a Uri, if the drawable is a vector or if the image asset you generated, includes an XML along with all the other PNG files.
https://github.com/bumptech/glide/issues/2137