Archive

Posts Tagged ‘BitmapFactory’

Bitmap processing in Android

September 8th, 2010 No comments

I recently got somehow curious about some Sample Code I found in the web. The Problem is Simple. Let’s say we have a GameThread that want’s to draw a background image that fits the complete Screen. Before you draw the Bitmap to the Canvas you normally want to import the picture like this (maybe):

Bitmap mBackgroundImage = BitmapFactory.decodeResource(res, R.drawable.hase);
// this is curious
Log.i("DEBUG", "Imported Image width = " +
mBackgroundImage.getWidth() + " Heigth ="+
mBackgroundImage.getHeight());
// maybe expensive
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, 480, 800, true);

The open Question: Why scaling the picture if the source-image is already in 480×800 ? The picture will suffer from scaling besides the expensive scaling process. In this scenario the we have a fixed TargetDisplay-Size of 480×800. The Picture we are importing is already 480×800 Pixel. So far so good, but the LOG output says:

09-08 10:10:16.859: INFO/DEBUG(19137): Imported Image width = 720 Heigth =1200

Strange ? ! This comes from the default density settings which seem to be kind of unreliable. In my case it’s 240dpi but the BitmapFactory works with 160 dpi. If you want to skip the re-scaling part and want to import a Bitmap the “short” way you can do that with Options.

The first thing you should do is get the density of your Display:

final DisplayMetrics metrics = context.getResources().getDisplayMetrics();

Now we can wire some options for the decoding:

Options myOptions = new Options();
		myOptions .inScaled = false;
		myOptions .inScreenDensity = metrics.densityDpi;
		myOptions .inTargetDensity = metrics.densityDpi;

So now we are ready to load the Bitmap in the right scale & size:

Bitmap newPic =	BitmapFactory.decodeResource(_resources, R.drawable.hase, myOptions )