Search code examples
javaandroidkotlincanvasbitmap

Why does Bitmap.createBitmap return a Bitmap with a different size than specified and how to avoid it?


When I create a Bitmap and Canvas with the following code:

Bitmap bitmap = Bitmap.createBitmap(640, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);

and I put a breakpoint at the second line to display the preview, it turns out the created Bitmap's size is different than specified. It's supposed to be 640px wide, but the preview says it's 377px instead.

The height is scaled down by the same factor (640/377 is the same as 1737/1024) so I presume some unwanted scaling takes place there.

Android Studio debugger

Interestingly, bitmap.getWidth() returns 640.

I initially thought it might be the debugger's preview related issue, but I checked that when I load some images using:

BitmapFactory.decodeResource(context.resources, R.drawable.image)

and I scale them later to the desired width:

Bitmap.createScaledBitmap(bitmap, desiredWidthPx, targetHeightToKeepAspectRatio, false)

the debugger's preview shows them correctly, i.e. their size matches desiredWidthPx and targetHeightToKeepAspectRatio. So it's not the preview's issue.

For context: I stumbled upon this issue while working on a Bitmap with a specific width in pixels. The Bitmap is going to be printed by a thermal printer later on, so the size must not depend on the Android device's screen size, density and so on. I started debugging this issue after realizing the printer printed around 60% of the image (it was cropped horizontally), e.g. something like this:

Printed paper

I'm not sure exactly what's going on, but by looking at the printouts, I think it's reasonable to suspect the scaling to be the issue here.


Solution

  • Bitmap size in the debug preview is limited to 1024px regardless of the method used to create it. Similar question and issue tracker. Your issue with the printer is not related to it.