调整Bitmap时Android的质量很差

时间:2013-01-17 08:10:08

标签: android bitmap resize

我在应用程序中调整一个图像位图的大小时遇到​​问题,图像质量会下降。

我调整大小的代码如下..

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight,
            Config.ARGB_8888);

    float ratioX = newWidth / (float) bm.getWidth();
    float ratioY = newHeight / (float) bm.getHeight();
    float middleX = newWidth / 2.0f;
    float middleY = newHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.postScale(ratioX, ratioY, middleX, middleY);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bm, middleX - bm.getWidth() / 2,
            middleY - bm.getHeight() / 2, paint);
    return scaledBitmap;
}

调整大小位图的任何好方法¿?

1 个答案:

答案 0 :(得分:0)

使用此代码,我希望它能为您提供帮助

    /***
 * This method is for aspect ratio means the image is set acc. to the aspect
 * ratio.
 * 
 * @param bmp
 *            bitmap passed
 * @param newWidth
 *            width you want to set for your image
 * @param newHeight
 *            hight you want to set for your image
 * @return bitmap
 */
public Bitmap resizeBitmap(Bitmap bmp, int newWidth, int newHeight) {
    Log.i(TAG,
            "height = " + bmp.getHeight() + "\nwidth = " + bmp.getWidth());
    if (bmp.getHeight() > newHeight || bmp.getWidth() > newWidth) {
        int originalWidth = bmp.getWidth();
        int originalHeight = bmp.getHeight();
        Log.i("TAG", "originalWidth = " + originalWidth
                + "\noriginalHeight = " + originalHeight);
        float inSampleSize;
        if (originalWidth > originalHeight) {
            inSampleSize = (float) newWidth / originalWidth;
        } else {
            inSampleSize = (float) newHeight / originalHeight;
        }
        newWidth = Math.round(originalWidth * inSampleSize);
        newHeight = Math.round(originalHeight * inSampleSize);
        Log.i("", "newWidth = " + newWidth + "\nnewHeight = " + newHeight);
        bitmap = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
    } else {
        bitmap = bmp;
        Log.i("", "bitmapWidth = " + bitmap.getWidth()
                + "\nbitmapHeight = " + bitmap.getHeight());
    }
    return bitmap;
}