简体   繁体   中英

Android: FileNotFoundException on an image in drawable

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM