android get Bitmap or sound from assets

前端 未结 5 1224
陌清茗
陌清茗 2020-12-08 06:34

I need to get Bitmap and sound from assets. I try to do like this:

BitmapFactory.decodeFile(\"file:///android_asset/Files/Numbers/l1.png\");
<
5条回答
  •  悲&欢浪女
    2020-12-08 07:36

    The accepted answer never closes the InputStream. Here is a utility method for getting a Bitmap in the assets folder:

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

提交回复
热议问题