ArithmeticException sometimes divides by zero

I have JAVA (runs on Android) that sometimes catches an ArithmeticException due to division by zero, although the inSampleSize variable is set to 1 before the loop and only multiplied by 2 each time. The following is the method as it is. Any idea what I'm missing here? Thank!

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;

    try {
        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
    } catch (ArithmeticException e) {
        LogUtil.Log("ArithmeticException=" + e.getMessage() + " inSampleSize=" + inSampleSize);
        Crashlytics.logException(e);
        inSampleSize=1;
    }
    LogUtil.Log("inSampleSize="+inSampleSize);
    return inSampleSize;
}
+4
source share
2 answers

Because height and halfHeight are inside this exception.

final int halfHeight = height / 2;

if height = 1 halfHeight will be 0 here. At the time you call

halfHeight / inSampleSize

you will get an ArithmeticException because halfHeight is 0.

: double BigDecimal, , .

0

, , 1 - 2, 0. 32 while inSampleSize 0. , Java int.

, :

int count = 0;
int inSampleSize = 1;
while (inSampleSize != 0) {
 count++;
 inSampleSize *= 2;
}

, inSampleSize , count 32.

, , 32 while? : reqWidth reqHeight 1.

, , :

calculateInSampleSize(options, 0, 0);

, .

reqWidth reqHeight , , , . , , View.getWidth() View.getHeight(), , , , , 0. , , , , reqWidth reqHeight , , 1, .

0

All Articles