Thursday, 5 January 2017

bitmapfactory - android - calculateInSampleSize, why does Math.round deal with height( height / reqHeight) when width > height?




I'm looking on 'developer.android.com' to scale down my bitmap file and I found one thing that I don't understand. so I appreciate you give me a little help.



Here's a snippet from developer.android.com



public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;

int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;

}


in if statement, when " if(width > height)" why do they calculate "(float)height / (float)reqHeight " ?



for example, width=600, height=800, reqWidth=100, reqHeight=100.



In this situation, inSampleSize would be 6 and the dimensions calculated are width=100, height=133. height is still above reqHeight..



so, can anyone explain me about this, please? sorry for complicated explanation but

I hope someone give me a idea. :)


Answer



All I can say is that their logic looks wrong :( Anyway this method is fairly simple so it shouldn't be that much of a problem for you to reimplement it with the correct conditions ! I mean when you take a look at decodeSampledBitmapFromResource, it only wants to reduce the Bitmap to make it fit into the desired bounds, so this has to be an error.



EDIT :: That looks even worse as to me it won't work for some cases. Let's say you have width = 200 and height = 600. You set your max bounds at width = 100 and height = 500. You have height > width, yet if you want them both to fit the return result inSampleSize has to be 200/100 and not 600/500.
So basically if you reimplement the method, I would do it this way :



public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image

final int height = options.outHeight;
final int width = options.outWidth;

int stretch_width = Math.round((float)width / (float)reqWidth);
int stretch_height = Math.round((float)height / (float)reqHeight);

if (stretch_width <= stretch_height)
return stretch_height;
else
return stretch_width;

}


But that looks like too many issues with their code for me to believe I understood its point correctly !


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...