0

I've encountered totally bizarre behavior in the way Android loads bitmaps into ImageView. For example, I have a 500x313 image file called urimg_01.jpg. With this code:

        img.setImageResource(R.drawable.urimg_01);
        Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
        Log.v(TAG,"---------------------> bitmap width = "+bitmap.getWidth());
        Log.v(TAG,"---------------------> bitmap height = "+bitmap.getHeight());

the ImageView bitmap is 750x470. (I have a Nexus S with 480x800 display.)

With this code, which reads a copy of the same file located in getFilesDir():

            Log.v(TAG,"image file is "+filelist[0].getAbsolutePath());
            FileInputStream fis = new FileInputStream(filelist[0]);
            FileDescriptor fd = fis.getFD();
            Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);
            if (bitmap != null) {
                Log.v(TAG,"---------------------> bitmap width = "+bitmap.getWidth());
                Log.v(TAG,"---------------------> bitmap height = "+bitmap.getHeight());
                img.setImageBitmap(bitmap);
                fis.close();
            }

the ImageView bitmap is 500x313, as expected.

In the case of setImageResource(), where the devil is it getting 750x470 from?? And how do I get it to use the correct dimensions for resources in drawable?

Richard Eng
  • 1,954
  • 6
  • 23
  • 32

2 Answers2

0

Your resource is being scaled up because it's probably stored in a medium density folder and you're using a high density device. See Bitmap getWidth returns wrong value for details.

Community
  • 1
  • 1
kabuko
  • 36,028
  • 10
  • 80
  • 93
0

here you get your bitmap

Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);

now scale it according to device height and width

     Display display=this.getWindowManager().getDefaultDisplay();
    int w=display.getWidth();
    int h=display.getHeight();
    Bitmap newBitmap=Bitmap.createScaledBitmap(oldBitmap, w, h, false);
    //now setImage to background with new Bitmap

One important thing "this" should be activity context :) cheers

Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87