如何获取drawable的File实例?

时间:2012-06-25 07:49:06

标签: android file uri drawable fileinputstream

以下是我应对徽标打印的代码。徽标放在res / drawable文件夹中。当我运行应用程序时,它会抛出:

java.io.FileNotFoundException: /android.resource:/com.android.test/2130837505 (No such file or directory).

有什么建议吗?

    public  boolean printLogo()
    {
      Uri logo_path = Uri.parse("android.resource://com.android.test/" + R.drawable._logo);
      File logo = new File(logo_path.toString());
      byte[] logo_bytes = new byte[(int) logo.length()];
      System.out.print("Length:" + logo.length());
      FileInputStream fs;
      try {
          fs = new FileInputStream(logo);
          fs.read(logo_bytes);
          fs.close();
          mChatService.write(logo_bytes);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }catch (IOException e) {
          e.printStackTrace();
      }
      return true;
    }

2 个答案:

答案 0 :(得分:10)

是的,你应该在资产或原始目录下添加这种类型的资源......

但是如果你have any limitation你只需要字节数组就可以试试

Bitmap bmp= BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.icon_resource);

  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
   byte[] byteArray = stream.toByteArray();

答案 1 :(得分:1)

首先将您的图片资源放在assets文件夹下,然后使用AssetManager从资源中获取InputStream

AssetManager mgr = context.getAssets(); 
FileInputStream fin = (FileInputStream)mgr.open("path/filename");

path不应包含assets文件夹。