从assets文件夹加载图像

17

我有一个Android应用程序,其中有多个图像在assets文件夹中。现在我想要创建这些图像的数组。我的问题是:当我们的图像在drawable中时,我们可以像下面这样创建一个数组:

int x[] = {
    R.drawable.ss,
    R.drawable.aa, R.drawable.sk,
    R.drawable.xx
};

等等。当我的图片位于资产文件夹中时,我该如何创建与上面相同的图像数组?我想在类级别上创建一个数组。


你可以使用一个字符串数组来存储文件名。 - JRowan
使用搜索 https://dev59.com/YWsz5IYBdhLWcg3w0bOl 加载图像。 - Lebedevsd
4个回答

28

您需要像下面这样逐个读取图像:

您可以使用AssetManager的open()方法获取InputStream,然后使用BitmapFactory的decodeStream()方法获取位图。

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

6
如果您的图片存储在资产目录中的图像文件夹中,那么您可以按以下方式获取图像列表:
private List<String> getImage(Context context) throws IOException {
      AssetManager assetManager = context.getAssets();
      String[] files = assetManager.list("image");   
      List<String> it = Arrays.asList(files);
      return it; 
}

我想在类级别上声明它。这可行吗? - Doctor Who
然后你需要先获取上下文,然后才能获取资产。 - Sunil Kumar
你能举个例子详细解释一下吗? - Doctor Who
我已经编辑了上面的代码,如果你想在类级别中使用,那么你应该像上面一样传递Context,但是请确保先用Activity或ApplicationContext初始化Context。 - Sunil Kumar

4
 // load image from asset folder 
        try {
            // get input stream
            InputStream ims = getAssets().open("avatar.jpg");
            // load image as Drawable
            Drawable d = Drawable.createFromStream(ims, null);
            // set image to ImageView
            mImage.setImageDrawable(d);
        }
        catch(IOException ex) {
            return;
        }

  or you can create drawable array
    Drawable d []={d};

1
您对drawables和assets的含义有误。您可以创建“drawable”数组,因为所有的drawable都有自己的R id(如R.drawable.ss),所以如果您有适当的上下文,可以使用指定的整数来获取drawable。
管理文件(如图片)的另一种方法是使用assets。如果您想通过它们的id来管理图像,则必须将这些图像添加到drawable中。否则,assets文件必须像dir中的普通文件一样进行管理。
您必须从assets中获取文件 AssetManager am=this.getAssets();,然后准备文件以进行读写。如果您有图像,可以这样做:
try {    
    Bitmap bmp=BitmapFactory.decodeStream(am.open("009.gif"));
    imageView.setImageBitmap(bmp);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接