Wrong image sizes in android when using bitmap

I have a .png image file stored as a resource in an Android app. In my code, I place a new Bitmap instance from this image as follows:

Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.imgName); 

But when I read image sizes from a Bitmap object using the getWight () and getHeight () methods,

 int width = img.getWidth(); int height = img.getHeight(); 

I get different results from the original image ... Can someone explain to me what I am missing and how can I get the image size?

(My project complies with android 2.2 - API 8)

Edit: Good - figured out how to get real sizes: the inJustDecodeBounds value for the property of the BitmapFactory.Options class is true:

 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.drawable.imgName, options); width = options.outWidth; height = options.outHeight; 

Now the problem is that the decoder returns null when we send the Options argument, so I need to decode again, as before (without Options argument ...) to retrieve Bitmap instance -bizarre, isnt this?

+6
source share
2 answers

To get the exact use of a resource image:

  BitmapFactory.Options o = new Options(); o.inScaled = false; Bitmap watermark = BitmapFactory.decodeResource(context.getResources(), id, o); 

Disables automatic scaling of screen density.

Update: I am sure you understand this, but inJustDecodeBounds does just that, it finds the dimensions. You will not receive the image. This option is typically used for custom scaling. You end up calling decodeResource twice, the second time parameter:

 options.inJustDecodeBounds = false; 

and making any changes to the parameters based on your:

 width = options.outWidth; height = options.outHeight; 
+8
source

Android scales your image for different densities (for different resolutions and screen sizes). Put a separate copy of your image in drawable-ldpi, drawable-hdpi, drawable-xhdpi, drop-down folders.

+3
source

Source: https://habr.com/ru/post/905935/


All Articles