簡體   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