hqt
hqt

Reputation: 30284

Android : cannot read image in assets folder and assign to imageview

I have a file food.jpg in assets folder. I have try many ways. but I still cannot get this image into imageView. when run, instead of display image "food.jpg", it displays image that I have declared in xml file. (that image is in drawable folder).

The first way is:

int asset_id = context.getResources().getIdentifier("food", "drawable", context.getPackageName());
imageView.setImageResource(asset_id);

The second way is:

AssetManager assetManager = context.getAssets();
InputStream istr;
try {
         istr = assetManager.open("food");
         Bitmap bitmap = BitmapFactory.decodeStream(istr);
         imageView.setImageBitmap(bitmap);
                 istr.close();
        } catch (IOException e) {
            e.printStackTrace();
}

Please teach me how to fix this problem.

thanks :)

Upvotes: 0

Views: 3072

Answers (2)

user1381827
user1381827

Reputation:

Your code is working fine. just add image MIME-Type(.jpg,jpeg,.png... etc) in below line:

istr = assetManager.open("ceo.jpg");

full code for your refrance

AssetManager assetManager = getAssets();
        InputStream istr;
        try {
            istr = assetManager.open("ceo.jpg");
            Bitmap bitmap = BitmapFactory.decodeStream(istr);
            imageView.setImageBitmap(bitmap);
            istr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

Upvotes: 1

Umesh Lakhani
Umesh Lakhani

Reputation: 2412

Try this Code...

try {
        // get input stream
        InputStream ims = getAssets().open("food.jpg");
        // load image as Drawable
        Drawable d = Drawable.createFromStream(ims, null);
        // set image to ImageView
        imgNews.setImageDrawable(d);
    } catch (Exception ex) {
        return;
    }
}

Upvotes: 0

Related Questions