Android get image path from drawable as string

前端 未结 5 588
天涯浪人
天涯浪人 2020-12-04 19:15

Is there any way that I can get the image path from drawable folder in android as String. I need this because I implement my own viewflow where I\'m showing the images by us

相关标签:
5条回答
  • 2020-12-04 19:56

    If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.

        InputStream stream = getAssets().open("image.png");
        Drawable d = Drawable.createFromStream(stream, null);
    
    0 讨论(0)
  • 2020-12-04 20:06

    These all are ways:

    String imageUri = "drawable://" + R.drawable.image;
    

    Other ways I tested

    Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
    Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
    
    String path = path.toString();
    String path = otherPath .toString();
    
    0 讨论(0)
  • 2020-12-04 20:12

    based on the some of above replies i improvised it a bit

    create this method and call it by passing your resource

    Reusable Method

    public String getURLForResource (int resourceId) {
        //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
        return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
    }
    

    Sample call

    getURLForResource(R.drawable.personIcon)
    

    complete example of loading image

    String imageUrl = getURLForResource(R.drawable.personIcon);
    // Load image
     Glide.with(patientProfileImageView.getContext())
              .load(imageUrl)
              .into(patientProfileImageView);
    

    you can move the function getURLForResource to a Util file and make it static so it can be reused

    0 讨论(0)
  • 2020-12-04 20:15

    I think you cannot get it as String but you can get it as int by get resource id:

    int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
    
    0 讨论(0)
  • 2020-12-04 20:20

    First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder

    Sample Code

    File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
            if(!imageFile.exists()){//file doesnot exist in SDCard
    
            imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
            }
    
    0 讨论(0)
提交回复
热议问题