Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect image dimensions in android when using Bitmap

Tags:

android

I have.png image file stored as a resource in my android application. In my code, i am allocationg new Bitmap instance from that image as follow:

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

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

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

I am getting different results from the original image... Can some one explain me what am I missing, and how can I retreive the image size?

(My project is complied with android 2.2 - API 8)

Edit: Ok - found out how to get the real dimensions: setting inJustDecodeBounds property of the BitmapFactory.Options class to true as follow:

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

The problem now is that the decoder returns null when we send Options argument, so I need to decode again like I did before (without Options argument...) to retrieve Bitmap instance -bizarre, isnt it?

like image 638
ET. Avatar asked Jan 13 '12 17:01

ET.


People also ask

What is bitmap image in Android?

A bitmap (or raster graphic) is a digital image composed of a matrix of dots. When viewed at 100%, each dot corresponds to an individual pixel on a display. In a standard bitmap image, each dot can be assigned a different color. In this instance we will simply create a Bitmap directly: Bitmap b = Bitmap.


2 Answers

To get exact resource image use:

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

This turns off the automatic screen density scaling.

Update: I'm sure you realized this by now, but inJustDecodeBounds does just that, it finds the dimensions. You will not get an image. That option is generally for doing custom scaling. You end up calling decodeResource twice, the second time setting:

options.inJustDecodeBounds = false;

and making any adjustments to the options based on your:

width = options.outWidth;
height = options.outHeight;
like image 64
Anthony Avatar answered Nov 15 '22 19:11

Anthony


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

like image 30
manjusg Avatar answered Nov 15 '22 19:11

manjusg