What is the unit of bitmap.getWidth() or bitmap.getHeight()

13,103

Solution 1

It's pixel. In Java code you usually work with pixels, e.g. a view's width and height.

Solution 2

bitmap.getWidth() returns width in dp unit or densitiy.

To get dpi (density per inch) for a device, use

float dpi = context.getResources().getDisplayMetrics().density;

To convert dp to px

float px = dp * dpi;

and to convert px to dp

float dp = px/dpi;

Solution 3

After Hours of Experimenting I found that it actually return height in dp units.You can verify it by changing the device screen in emulator.

Share:
13,103

Related videos on Youtube

Neoh
Author by

Neoh

Research Scientist. Hobby programmer.

Updated on September 16, 2022

Comments

  • Neoh
    Neoh over 1 year

    The developers website simply states that getHeight() will return the bitmap's height, but can someone tell me that is in pixel unit or dp unit?

    • Neoh
      Neoh almost 11 years
      That is view.getHeight(), not bitmap. The downvote is ridiculous, I won't ask this if I can easily google that information.
  • Vulovic Vukasin
    Vulovic Vukasin over 7 years
    its actually in density pixels.
  • Zanna
    Zanna over 5 years
    DPI = Dot Per Inch; px = dp * DPI / 160
  • Saravana Kumar K R
    Saravana Kumar K R over 5 years
    @Zanna what is the need for dividing it by 160?
  • Zanna
    Zanna over 5 years
    1dp corresponds to about (not exactly) 1/160 inch (0.15875mm). Or 1dp corresponds to 1px on a screen resolution of 160DPI (DENSITY_MEDIUM). Your formula is correct, but the variable name "dpi", float dpi = DisplayMetrics().density, is misleading, because that is a scale factor, according to the documentation (and it is not even a density, despite its name). The screen resolution (the linear density of pixels on the unit length of an inch) is generally expressed in DPI and it is in DisplayMetrics.densityDpi. While DisplayMetrics.density = DisplayMetrics.densityDpi / 160, is a scale factor.
  • knjk04
    knjk04 about 5 years
    @VulovicVukasin I don't think it is. I just logged the height and width of a bitmap and then compared the output to the height and width given by the details of an image from a file manager (which I presume gives it in pixels). They match, so I think it is pixels.
  • gregoiregentil
    gregoiregentil over 4 years
    How is it possible a selected answer with 15 up votes is a WRONG answer? It's in dp not in pixel.
  • Emmanuel Conradie
    Emmanuel Conradie over 2 years
    This is the wrong way around