2

I'm trying to resize a bitmap using inDensity and inTargetDensity following @colt-mcanlis' instructions explained at 1, 2 and 3.

So far so good, good documentation, great video. The problem is that the resulting sizes for the image makes no sense to me.

For example if I use following values:

  • srcWidth is 11774px and srcHeight is 6340px
  • dstWidth is 1440px and dstHeight is 2392px

The code I'm using is:

options.inScaled = true;
options.inSampleSize = 8;
options.inDensity = srcWidth;
options.inTargetDensity = dstWidth * 8;
options.inSampleSize;
imageBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.image, options);

And the resulting image has width 70px and height 38px, instead 1440x2393.

I tried without using inSampleSize, and I get a very similar result. Then I assume the problem is with inTargetDensity and inDensity.

I went to the documentation and found the following:

inDensity

int inDensity The pixel density to use for the bitmap...

As far as I know, to calculate a density I need a width, height and a display size but a display size doesn't make sense to me in this context, since I just want to calculate inDensity and inPixelDensity independent of a display size.

So, what am I doing wrong here ?

Community
  • 1
  • 1
RobertoAllende
  • 8,744
  • 4
  • 30
  • 49
  • Did you eventually understand how to use properly `inDensity` and `inTargetDensity` ? The documentation sucks, and I m going crazy because the result is not what I was expecting. – GVillani82 May 25 '17 at 16:55

2 Answers2

1

I was following Loading Large Bitmaps Efficiently by the book, but was running into the problem that the decoded bitmap ended up having way larger dimensions even than the original image (options.outWidth / options.outHeight).

I noticed that after the "decode bounds" step, inTargetDensity had a larger value than inDensity, and ultimately found that to be the cause of the larger decoded bitmap. Not sure exactly when playing with anything different on this fields would be useful...

But setting options.inTargetDensity = options.inDensity after the "decode bounds" step, worked for having the bitmap be decoded at the expected size (according to the inSampleSize you calculate).

Looking forward to the "more straightforward" API that Romain Guy announced in Google I/O (2018) :D

droid256
  • 404
  • 5
  • 15
0

If you just want to resize an image while decoding, inSampleSize option is enough, but, because the aspect ratio of original and target images are not the same, you can't get the expected result through inSampleSize option directly, you need to do some extra crop operations after resizing. You can refer to the following guide for details: http://developer.sonymobile.com/2011/06/27/how-to-scale-images-for-your-android-application/

tonykwok
  • 371
  • 2
  • 10