21

I have a jpg image in my android application drawable folder which resolution is 1000x600. I load that image to bitmap like this

 Bitmap bitMap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

After this I call bitMap .getWidth() which returns 1500. How it can be? And how to get the right width and height of image?

Zain
  • 37,492
  • 7
  • 60
  • 84
narek.gevorgyan
  • 4,165
  • 5
  • 32
  • 52

1 Answers1

43

This is probably because of differing densities. Your resource is probably stored in a medium density folder, but your device is hdpi. Medium density is 160dpi, high density is 240dpi. Thus your bitmap is scaled to 1.5x the size it was originally. See the document on multiple screens for more info.

If resources are not available in the correct density, the system loads the default resources and scales them up or down as needed to match the current screen's density.

If you intended this to be for high density put it in drawable-hdpi instead of drawable or drawable-mdpi.

Update:

If you want it to ignore density, put it in a drawable-nodpi folder. Also from the same doc:

The easiest way to avoid pre-scaling is to put the resource in a resource directory with the nodpi configuration qualifier. For example:

res/drawable-nodpi/icon.png

When the system uses the icon.png bitmap from this folder, it does not scale it based on the current device density.

You can also see here for more information on providing and grouping resources.

starball
  • 20,030
  • 7
  • 43
  • 238
kabuko
  • 36,028
  • 10
  • 80
  • 93
  • Upvoted for the drawable-nodpi suggestion. I have 512x512 pixel bitmaps which I need to draw in a 4x4 grid, and was running out of memory because the original bitmaps were scaled up to 1408x1408. – Huw Walters Aug 11 '19 at 09:03