如何将本地图片文件转换为Android资源ID?
Hey there! Let's start with a crucial clarification: Local image files stored in your phone's internal storage or SD card do NOT have an Android resource ID (the int value you're looking for).
Resource IDs are unique integer values generated at build time exclusively for assets packaged inside your app's res/ directory—things like drawables, layouts, strings, etc. Since your local files are external to your app's pre-packaged resources, the Android system never assigns them a standard resource ID.
So What Can You Do Instead?
It depends on why you need an int ID, but here are common practical workarounds:
If you need to use the image in UI components: You don't need a resource ID at all. Use the Bitmap you already have, or load the file directly using its path:
// Load Bitmap from the local file path Bitmap myBitmap = BitmapFactory.decodeFile("/storage/emulated/0/my_photo.jpg"); // Set it to an ImageView imageView.setImageBitmap(myBitmap);For smoother handling (like caching or resizing), use an image-loading library like Glide:
Glide.with(this) .load(new File("/storage/emulated/0/my_photo.jpg")) .into(imageView);If you need a unique integer identifier for the file: Create your own mapping. For example, use a
HashMap<String, Integer>to link file paths to custom integer IDs you define, or store file details (path + custom ID) in a local database. This lets you reference the file with an int whenever you need to.If you're working with an API that requires a resource ID: Most such APIs have overloads that accept a
Uri,InputStream, orBitmapinstead. For example, instead ofsetImageResource(int resId), usesetImageBitmap(bitmap)orsetImageURI(Uri.fromFile(new File(filePath))).
Key Takeaway
Resource IDs are tied to app-packaged resources, not external files. You'll need to use direct file loading or custom identifiers instead of trying to get a system-generated int ID for local images.
内容的提问来源于stack exchange,提问作者Sudip

