2011-12-14 7 views
30

アセットからビットマップとサウンドを取得する必要があります。androidアセットからビットマップまたはサウンドを取得

BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png"); 

そして、このように:私はこのようにやろう

getBitmapFromAsset("Files/Numbers/l1.png"); 
    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; 
    } 

しかし、私はちょうど、自由空間ではなく、画像を取得します。

これを行う方法?

答えて

98
public static Bitmap getBitmapFromAsset(Context context, String filePath) { 
    AssetManager assetManager = context.getAssets(); 

    InputStream istr; 
    Bitmap bitmap = null; 
    try { 
     istr = assetManager.open(filePath); 
     bitmap = BitmapFactory.decodeStream(istr); 
    } catch (IOException e) { 
     // handle exception 
    } 

    return bitmap; 
} 

パスは単にファイル名fx bitmap.pngです。あなたはサブフォルダビットマップを使用している場合/そのビットマップ/ bitmap.png

+0

これは正しい方法です。しかし、私は絵だけではなく自由空間しか見ません。私は何を間違えたのですか? – Val

+0

画像を確認してください...デバッグとステップスルーをお試しください。写真が置かれている場所とその場所についてもっと詳しく説明してください。 – Warpzit

+0

サブフォルダを使用する場合は、大文字と小文字の区別を覚えておいてください。 – Warpzit

10

使用我々はより頻繁にメモリオーバーフロー例外と会うビットマップをデコードしながらその

try { 
    InputStream bitmap=getAssets().open("icon.png"); 
    Bitmap bit=BitmapFactory.decodeStream(bitmap); 
    img.setImageBitmap(bit); 
} catch (IOException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 

更新

作業このコードであれば画像サイズ非常に大きいです。したがって、記事How to display Image efficientlyを読むことが役に立ちます。

6

受け入れ可能な回答は決してInputStreamを閉じません。アセットフォルダにBitmapを取得するためのユーティリティメソッドは以下のとおりです。

/** 
* Retrieve a bitmap from assets. 
* 
* @param mgr 
*   The {@link AssetManager} obtained via {@link Context#getAssets()} 
* @param path 
*   The path to the asset. 
* @return The {@link Bitmap} or {@code null} if we failed to decode the file. 
*/ 
public static Bitmap getBitmapFromAsset(AssetManager mgr, String path) { 
    InputStream is = null; 
    Bitmap bitmap = null; 
    try { 
     is = mgr.open(path); 
     bitmap = BitmapFactory.decodeStream(is); 
    } catch (final IOException e) { 
     bitmap = null; 
    } finally { 
     if (is != null) { 
      try { 
       is.close(); 
      } catch (IOException ignored) { 
      } 
     } 
    } 
    return bitmap; 
} 
+0

これは受け入れられた答えでなければなりません!あなたがストリームを閉じたくないのは、あなたが後で得るかもしれない例外の種類がネイティブの例外になるからです。それはあなたがそれを捕まえることができないことを意味します: –

関連する問題