Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get an uri of an image resource in android

Tags:

android

uri

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.

like image 582
user602874 Avatar asked Feb 04 '11 09:02

user602874


People also ask

How do I find the URI of a picture?

You should use ContentResolver to open resource URIs: Uri uri = Uri. parse("android. resource://your.package.here/drawable/image_name"); InputStream stream = getContentResolver().

How do I get URI resources?

Occasionally however, you will need to get the actual URI of a resource. All you need to do is replace the package name with your app's package name, as defined in the manifest, and the resource ID of the resource you would like to use. Uri resourceURI = Uri. parse("android.

What is the URI in Android?

A URI is a uniform resource identifier while a URL is a uniform resource locator.

How do I turn a picture into a drawable URL?

AQuery aq = new AQuery(this); aq.id(view). image("http://yourserver/yourimage.png", true, true, 300, new BitmapAjaxCallback() { @Override public void callback(String url, ImageView imageView, Bitmap bitmap, AjaxStatus status) { Drawable drawable = new BitmapDrawable(getResources(), bm); } });


2 Answers

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);

like image 163
Axarydax Avatar answered Oct 01 '22 03:10

Axarydax


Here is a clean solution which fully leverages the android.net.Uri class via its Builder pattern, avoiding repeated composition and decomposition of the URI string, without relying on hard-coded strings or ad hoc ideas about URI syntax.

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(); 

Minimally more elegant with Kotlin:

fun Context.resourceUri(resourceId: Int): Uri = with(resources) {     Uri.Builder()         .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)         .authority(getResourcePackageName(resourceId))         .appendPath(getResourceTypeName(resourceId))         .appendPath(getResourceEntryName(resourceId))         .build() } 
like image 22
Uli Avatar answered Oct 01 '22 04:10

Uli