how to get an uri of an image resource in android how to get an uri of an image resource in android android android

how to get an uri of an image resource in android


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


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


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