按比例调整位图大小

syn*_*nic 5 android

我有一个位图...如果位图的高度大于maxHeight,或者宽度大于maxWidth,我想按比例调整图像的大小,使其适合maxWidth X maxHeight.这是我正在尝试的:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

java.lang.IllegalArgumentException: bitmap size exceeds 32bits

我在这做错了什么?

oli*_*oli 8

你的scaleWidth和scaleHeight应该是比例因子(所以不是很大的数字)但你的代码似乎传递了你正在寻找的实际宽度和高度.因此,您最终会大幅增加位图的大小.

我认为代码还有其他问题来导出scaleWidth和scaleHeight.首先,您的代码总是有scaleWidth = widthscaleHeight = height,并且只更改其中一个,因此您也会扭曲图像的宽高比.如果您只想调整图像大小,那么您应该只有一个scaleFactor.

另外,为什么你的if语句有效地检查maxRatio> ratio?你不应该检查宽度> maxWidth高度> maxHeight