Android: FileNotFoundException on an image in drawable

北战南征 提交于 2019-12-25 06:37:55

问题


I'm trying to use this code that I've seen on multiple posts throughout stackoverflow

    public static Bitmap loadBitmap(Context context, String filename) throws IOException {
           AssetManager assets = context.getResources().getAssets();
           InputStream buf = new BufferedInputStream((assets.open("drawable/" + filename)));
           Bitmap bitmap = BitmapFactory.decodeStream(buf);

           return bitmap;
   }

but I'm getting a "FileNotFoundException: drawable/filename". I definitely have a file with the name I'm trying to load in the drawable folders. Any ideas? I've tried with and without the file extension, tried putting the file into every folder and tried multiple phones/emulator.


回答1:


The AssetManager is intended to access the data in the assets folder. So in your example, it looks for assets/drawable/filename and does not find anything.

To get a resource from drawable, one should use

Drawable d = getResources().getDrawable(R.drawable.filename);

If you're sure it's a bitmap, you can do it like so:

Bitmap bm = ((BitmapDrawable)getResources()
                .getDrawable(R.drawable.filename)).getBitmap();



回答2:


You can do it like this...

// load image from Assets folder
        // get input stream
        InputStream mIms = getAssets().open("ic_launcher.png");
        // load image as Drawable
        Drawable mDraw = Drawable.createFromStream(mIms, null);
        // set image to ImageView
        mIms.setImageDrawable(mDraw);


来源:https://stackoverflow.com/questions/15847954/android-filenotfoundexception-on-an-image-in-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!