Load an image from assets folder

后端 未结 8 1795
天命终不由人
天命终不由人 2020-11-28 07:06

I am trying to load an image from the asset folder and then set it to an ImageView. I know it\'s much better if I use the R.id.* for t

8条回答
  •  被撕碎了的回忆
    2020-11-28 07:39

    Some of these answers may answer the question but I never liked any of them so I ended up writing this, it my help the community.

    Get Bitmap from assets:

    public Bitmap loadBitmapFromAssets(Context context, String path)
    {
        InputStream stream = null;
        try
        {
            stream = context.getAssets().open(path);
            return BitmapFactory.decodeStream(stream);
        }
        catch (Exception ignored) {} finally
        {
            try
            {
                if(stream != null)
                {
                    stream.close();
                }
            } catch (Exception ignored) {}
        }
        return null;
    }
    

    Get Drawable from assets:

    public Drawable loadDrawableFromAssets(Context context, String path)
    {
        InputStream stream = null;
        try
        {
            stream = context.getAssets().open(path);
            return Drawable.createFromStream(stream, null);
        }
        catch (Exception ignored) {} finally
        {
            try
            {
                if(stream != null)
                {
                    stream.close();
                }
            } catch (Exception ignored) {}
        }
        return null;
    }
    

提交回复
热议问题