0

This error in stack overflow has many results, but no one matches my case. :(

I want to resize a bitmap , and, I built a method to do this stuff like this:

    public static Bitmap resizeBitmap(Bitmap image, float size, Bitmap backgroundImg) {

    int bitmapWidth = image.getWidth();
    int bitmapHeight = image.getHeight();

    float scaleWidth = (backgroundImg.getWidth() * size) / bitmapWidth;
    float scaleHeight = (float) (image.getHeight() / image.getWidth()) * scaleWidth;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    Log.d("===>", "bitmapWidth: " + bitmapWidth + " bitmapHeight: " +   bitmapHeight);

    return Bitmap.createBitmap(image, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
}

The crashes happens in the Bitmap.createBitmap(), something like this:

    java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:810)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:720)
    at com.watermark.androidwm.utils.BitmapUtils.resizeBitmap(BitmapUtils.java:154)

This method can resize the input bitmap according to the size of another image (backgroundImg). I can make sure the input Bitmap (image) is not null and the log shows:

D/===>: bitmapWidth: 1808 bitmapHeight: 1678

Obviously, the width and the height are bigger than 0. I don't know what's wrong with this method, and I have tried many times, found that if I put a bigger image (1024x839 ,etc) as the input Bitmap, the method crashes. If I load a small image as Bitmap, the method works well.

I load the input bitmap from the resource, drawable, like this:

    private Bitmap getBitmapFromDrawable(@DrawableRes int imageDrawable) {
         return BitmapFactory.decodeResource(context.getResources(), imageDrawable);
}

I don't know if this has any relationship with the exception, anyone can help me? thanks.

Ashvin solanki
  • 3,679
  • 1
  • 17
  • 49
  • 1
    `(float) (image.getHeight() / image.getWidth())` doesn't do floating point division: it does integer division, then widens the result to float. Remove the brackets, so that height is widened to float first, with the consequence that the width is promoted to float too: `(float) image.getHeight() / image.getWidth()`. – Andy Turner Sep 09 '18 at 13:52
  • You are right, the 0 is scaleHeight, this cannot be 0. – Yizheng Huang Sep 09 '18 at 14:13

0 Answers0