【问题标题】:Android Show image by pathAndroid 按路径显示图片
【发布时间】:2010-09-11 14:17:47
【问题描述】:

我想在 imageview 中显示图像而不使用 id。

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

     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());
    }

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

【问题讨论】:

    标签: android assets


    【解决方案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 文件夹中。

    【讨论】:

    • 我不想使用资源 ID。我会将所有图像放在资产中。
    【解决方案2】:

    您也许可以将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);
    

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

    【讨论】:

    • 我说我不想使用 id,
    • 我能问一下为什么吗?不幸的是,我认为我的方法是“不使用 ids”但仍然将它们放在原始资源目录中的唯一方法;否则就像你说的那样把它们放在资产中。
    【解决方案3】:

    试试{ // 获取 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();
      } 
    

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

    喜欢

    assest -> image -> somefolder -> some.jpg

    那么路径就是

    图像/somefolder/some.jpg

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 2018-06-09
      • 2015-10-21
      • 2013-03-10
      • 1970-01-01
      • 2018-12-11
      • 2014-02-28
      相关资源
      最近更新 更多