【问题标题】:How to open an image that is stored in a folder under Assets in android如何打开存储在android资产下文件夹中的图像
【发布时间】:2014-09-11 19:30:08
【问题描述】:

我在 android studio 中的 App 下创建了一个资产文件夹目录,其中包含 Build、Libs 和 Src,我在其中分别放置了带有图像的文件夹。我有一个问题,我无法在该文件名或路径中找到该文件,但我知道它是正确的,请告诉我该怎么做,因为我很难过。该文件位于此目录 assets/profileicon/26.png 中,数字由 profileIconTag 确定(在本例中为 26)现在我为 .open() 做正确的路径名了吗?

AssetManager assetManager = getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open("/profileicon/" + profileIconTag + ".png");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);

    profileIcon.setImageBitmap(bitmap);

【问题讨论】:

    标签: android bitmap assets


    【解决方案1】:

    您可以使用AssetManager 使用其open() 方法获取InputStream,然后使用BitmapFactory 的decodeStream() 方法获取Bitmap。检查this link。

    private Bitmap getBitmapFromAsset(String strName)
    {
        AssetManager assetManager = getAssets();
        InputStream istr = null;
        try {
            istr = assetManager.open(strName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        return bitmap;
    }
    

    【讨论】:

      【解决方案2】:

      检查资产文件夹是否在正确的路径中。

      InputStream bitmap=null;
      try {
          bitmap=getAssets().open(profileIconTag +".png");
          Bitmap bit=BitmapFactory.decodeStream(bitmap);
          profileIcon.setImageBitmap(bit);
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
         try{
          if(bitmap!=null)
          bitmap.close();
         }catch(Exception ex) {}
      }
      

      【讨论】:

      • 所以我不需要包含图片的路径?
      • 您的代码中有错误,您需要尝试并抓住您的 if(bitmap!=null)bitmap.close();这对我不起作用。
      • 好的,根据我在原始帖子中提供的信息,我将如何将路径名放在 .open() 中,因为我说过我的图像路径是 assets/profileicon/image .png
      • 去掉第一个斜线。
      • 我猜你传递的路径错误,试试@greenapps 提到的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2020-07-09
      • 2013-12-06
      • 2018-12-31
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多