android从资产中获取位图或声音

Val*_*Val 34 audio android assets android-bitmap

我需要从资产中获取位图和声音.我尝试这样做:

BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png");
Run Code Online (Sandbox Code Playgroud)

像这样:

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;
    }
Run Code Online (Sandbox Code Playgroud)

但我得到的是自由空间,而不是图像.

这该怎么做?

War*_*zit 119

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;
}
Run Code Online (Sandbox Code Playgroud)

路径只是你的文件名fx bitmap.png.如果你使用子文件夹位图/然后它的位图/ bitmap.png


Tof*_*mad 16

使用此代码工作

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();
}
Run Code Online (Sandbox Code Playgroud)

更新

在解码Bitmap时,如果图像大小非常大,我们更经常遇到内存溢出异常.所以阅读文章如何有效地显示图像将帮助您.


int*_*_32 11

简短的 Kotlin 版本:

assets
   .open(name)
   .use(BitmapFactory::decodeStream)
Run Code Online (Sandbox Code Playgroud)


Jar*_*ler 7

接受的答案永远不会结束InputStream.以下是获取Bitmapassets文件夹中的实用程序方法:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)