1

我想在不使用 id 的情况下在 imageview 中显示图像。

我会将所有图像放在原始文件夹中并打开

     try {
            String ss = "res/raw/images/inrax/3150-MCM.jpg";
             in = new FileInputStream(ss);
        buf = new BufferedInputStream(in);
        Bitmap bMap = BitmapFactory.decodeStream(buf);
        image.setImageBitmap(bMap);
        if (in != null) {
         in.close();
        }
        if (buf != null) {
         buf.close();
        }
    } catch (Exception e) {
        Log.e("Error reading file", e.toString());
    }

但这不起作用我想使用其路径而不是名称来访问图像

4

3 回答 3

1

使用 openRawResource() 读取字节流

这样的事情应该有效

InputStream is = context.getResources().openRawResource(R.raw.urfilename);

检查此链接

http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode

它清楚地说明了以下内容

虽然不常见,但您可能需要访问原始文件和目录。如果这样做,那么将文件保存在 res/ 中对您不起作用,因为从 res/ 读取资源的唯一方法是使用资源 ID

如果你想给出一个像你的代码中提到的文件名,你可能需要将它保存在 assets 文件夹中。

于 2010-09-11T14:29:06.750 回答
1

您也许可以使用Resources.getIdentifier(name, type, package)原始文件。这将为您获取 id,然后您可以继续使用 setImageResource(id) 或其他任何内容。

int id = getResources().getIdentifier("3150-MCM", "raw", getPackageName());
if (id != 0) //if it's zero then its not valid
   image.setImageResource(id);

是你想要的吗?虽然它可能不喜欢多个文件夹,但值得一试。

于 2010-09-11T20:44:45.203 回答
1

try { // 获取 AssetManager 的引用
AssetManager mngr = getAssets();

        // Create an input stream to read from the asset folder
        InputStream ins = mngr.open(imdir);

        // Convert the input stream into a bitmap
        img = BitmapFactory.decodeStream(ins);

  } catch (final IOException e) {
        e.printStackTrace();
  } 

这里图像目录是资产的路径

资产 -> 图像 -> somefolder -> some.jpg

那么路径将是

图像/somefolder/some.jpg

现在不需要图像的资源ID,您可以使用它在运行时填充图像

于 2010-09-11T23:02:03.377 回答