代码改变世界

【android】 资源路径

2012-08-07 20:18  Loull  阅读(3776)  评论(0编辑  收藏  举报
思路:

http://www.eoeandroid.com/thread-81618-1-1.html

如果图片在Drawable下面,可以把图片的ID给存到数据库,
想保存路径,可以把图片放在assets文件夹下面。

 

绝对路径:

http://blog.csdn.net/svrsimon/article/details/7079320

第一种方法:

第二种方法:

InputStream abpath = getClass().getResourceAsStream("/assets/文件名");
    //若要想要转换成String类型

    String path = new String(InputStreamToByte(abpath ));


    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

 

assets目录与res/raw、res/drawable目录的区别

http://superonion.iteye.com/blog/1424244

一、assets目录下的资源文件不会在R.java自动生成ID,所以读取assets目录下的文件必须指定文件的路径。可以通过AssetManager类来访问这些文件。比如要读取assets目录下的background.png:

Bitmap bgImg = getImageFromAssetFile( "background.png" );  
    
    /**  
     * 从assets中读取图片  
     */  
    private Bitmap getImageFromAssetsFile(String fileName)  
      {  
          Bitmap image = null;  
          AssetManager am = getResources().getAssets();  
          try  
          {  
              InputStream is = am.open(fileName);  
              image = BitmapFactory.decodeStream(is);  
              is.close();  
          }  
          catch (IOException e)  
          {  
              e.printStackTrace();  
          }   
          return image;  
      }

 

1. 图片放在sdcard中,

Bitmap imageBitmap = BitmapFactory.decodeFile(path) (path 是图片的路径,跟目录是/sdcard)

2. 图片在项目的res文件夹下面

//得到application对象

ApplicationInfo appInfo = getApplicationInfo();

//得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录,appInfo.packageName是应用程序的包)

int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);

//代码如下

public Bitmap getRes(String name) {

ApplicationInfo appInfo = getApplicationInfo();

int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);

return BitmapFactory.decodeResource(getResources(), resID);

}

3. 图片放在src目录下

String path = "com/xiangmu/test.png"; //图片存放的路径

InputStream is = getClassLoader().getResourceAsStream(path); //得到图片流

4.android中有个Assets目录,这里可以存放只读文件

 

//资源获取的方式为

InputStream is = getResources().getAssets().open(name);