Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proportionally resize a bitmap

Tags:

android

I've got a bitmap... and if the bitmap's height is greater than maxHeight, or the width is greater than maxWidth, I'd like to proportionally resize the image so that it fits in maxWidth X maxHeight. Here's what I'm trying:

    BitmapDrawable bmp = new BitmapDrawable(getResources(), PHOTO_PATH);

    int width = bmp.getIntrinsicWidth();
    int height = bmp.getIntrinsicHeight();

    float ratio = (float)width/(float)height;

    float scaleWidth = width;
    float scaleHeight = height;

    if((float)mMaxWidth/(float)mMaxHeight > ratio) {
        scaleWidth = (float)mMaxHeight * ratio;
    }
    else {
        scaleHeight = (float)mMaxWidth / ratio;
    }

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

    Bitmap out = Bitmap.createBitmap(bmp.getBitmap(), 
            0, 0, width, height, matrix, true);

    try {
        out.compress(Bitmap.CompressFormat.JPEG, 100, 
                new FileOutputStream(PHOTO_PATH));
    }
    catch(FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    }

I get the following exception:

java.lang.IllegalArgumentException: bitmap size exceeds 32bits

What am I doing wrong here?

like image 945
synic Avatar asked Jul 14 '10 14:07

synic


2 Answers

Your scaleWidth and scaleHeight should be scale factors (so not very big numbers) but your code seems to pass in the actual width and height you're looking for. So you're ending up massively increasing the size of your bitmap.

I think there are other problems with the code to derive scaleWidth and scaleHeight as well though. For one thing your code always has either scaleWidth = width or scaleHeight = height, and changes only one of them, so you're going to be distorting the aspect ratio of your image as well. If you just want to resize the image then you should just have a single scaleFactor.

Also, why does your if statement check for, effectively, maxRatio > ratio ? Shouldn't you be checking for width > maxWidth or height > maxHeight?

like image 176
oli Avatar answered Nov 08 '22 14:11

oli


This is because the value of scaleWidth or scaleHeight is too large,scaleWidth or scaleHeight is mean enlarge or shrink 's rate,but not width or height,too large rate lead to bitmap size exceeds 32 bits

matrix.postScale(scaleWidth, scaleHeight);
like image 42
wwwjiandan Avatar answered Nov 08 '22 13:11

wwwjiandan