繁体   English   中英

从assets文件夹加载图像

[英]Load Images from assets folder

我有一个Android应用程序,其中我有资产文件夹中的几个图像。 现在我想制作一组图像。 现在我的问题是: - 当我们的图像处于可绘制状态时,我们可以制作一个类似的数组

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

等等。 当我的图像在资源文件夹中时,如何制作与上面相同的图像数组。 我想在类级别创建一个数组。

您必须按图像读取图像,如下所示:

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

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

如果您的图像存储在资源目录中的图像文件夹中,那么您可以按照方式获取图像列表

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

你对drawables和assests有错误的含义。 您可以创建数组od“drawables”,因为所有drawable在R中都有自己的ID(如R.dawable.ss),因此如果您有适当的上下文,则可以使用指定的整数来获取drawable。

管理文件等图像的其他方式是有效的。 如果你想通过他们的ID管理图像,你必须添加这些图像做drawables。 换句话说,必须像在dir中的简单文件一样管理assests文件。

您必须从资产中获取文件AssetManager am=this.getAssets(); 然后准备文件进行读/写。 如果您有图像,可以执行以下操作:

try {    
    Bitmap bmp=BitmapFactory.decodeStream(am.open("009.gif"));
    imageView.setImageBitmap(bmp);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM