38

アセットからビットマップとサウンドを取得する必要があります。私はこのようにしようとします:

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

しかし、私は画像ではなく、ただの空き領域を取得します。

これを行う方法?

4

6 に答える 6

129
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/ を使用する場合、その bitmap/bitmap.png

于 2011-12-14T08:30:40.533 に答える
18

このコードを使用してください

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

アップデート

画像サイズが非常に大きい場合、Bitmap のデコード中にメモリ オーバーフロー例外が発生することがよくあります。したがって、画像を効率的に表示する方法の記事を読むと役立ちます。

于 2011-12-14T09:42:59.183 に答える
7

受け入れられた答えは決して閉じませんInputStreamBitmap以下は、assets フォルダー内のを取得するためのユーティリティ メソッドです。

/**
 * 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;
}
于 2015-01-19T09:34:35.227 に答える