2011-12-22 64 views
26

有没有什么办法可以从android中的可绘制文件夹获取图像路径作为字符串。我需要这个,因为我实现了我自己的视图流,通过在sd卡上使用它们的路径显示图像,但是我想在没有图像显示时显示默认图像。Android获取可绘制的图像路径作为字符串

任何想法如何做到这一点?

+1

当我读到[这里] [ 1]这是不可能的,因为这些文件在apk中。 [1]:http://stackoverflow.com/questions/6301493/android-get-path-of-resource – 2012-11-03 17:44:22

+0

这是正确的答案。 http://stackoverflow.com/a/25758286/7795876 – Hangman 2017-04-05 13:02:51

回答

-6

这样你就可以到达drawable文件夹中的特定图像。获取资源,然后指定你想要的形象进入:

Resources res = getResources(); 
Drawable drawable = res.getDrawable(R.drawable.myimage); 

欲了解更多信息,请参阅Drawable resources

+0

这不是回答这个问题。看起来他知道如何从可绘制文件夹中获取图像,但是R.drawable.myimage返回一个int值,并且他正在查找Resource文件夹的字符串路径。 – lagos 2014-10-21 09:37:45

-5

首先检查文件是否存在于SDCard中。如果在SD卡上的文件存在多年平均值,那么你可以从绘制文件夹

示例代码

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 
     } 
34

设置使用setImageResource(图)methodand通过默认的图像这些都是方法:

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

其它方式我测试过

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

我收到的文件格式不支持所有这些错误。 – NarendraJi 2016-06-02 08:37:19

+1

这样的模式返回FileNotFound异常 – 2016-09-22 16:32:12

+0

第一种方法不起作用 – mshah 2018-01-16 05:49:52

0

如果你打算从它的图像路径,最好使用Assets而不是试图找出可绘制文件夹的路径。

InputStream stream = getAssets().open("image.png"); 
    Drawable d = Drawable.createFromStream(stream, null); 
2

基础上,一些上述答复我临时有点

创建这个方法,并通过将您的资源

可重复使用的方法

public String getURLForResource (int resourceId) { 
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString(); 
} 

样品叫它致电

加载图像的
getURLForResource(R.drawable.personIcon) 

完全例如

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

您可以将功能getURLForResource移动到一个实用程序文件,并使其静态所以它可以重复使用