如何有效地调整位图的大小,而不会在Android中丢失质量

时间:2011-11-30 14:54:18

标签: android canvas bitmap resize surfaceview

我的Bitmap大小为320x480,我需要在不同的设备屏幕上展开它,我尝试使用它:

Rect dstRect = new Rect();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(frameBuffer, null, dstRect, null);

它有效,图像像我想要的那样填满整个屏幕,但图像像素化,看起来很糟糕。然后我试了一下:

float scaleWidth = (float) newWidth / width;
float scaleHeight = (float) newHeight / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(frameBuffer, 0, 0,
                width, height, matrix, true);
canvas.drawBitmap(resizedBitmap, 0, 0, null);

这次它看起来很完美,漂亮而且流畅,但是这段代码必须在我的主游戏循环中,并且每次迭代创建Bitmap都会使它非常慢。如何调整图像大小以使其不会像素化并快速完成?

找到解决方案:

Paint paint = new Paint();
paint.setFilterBitmap();
canvas.drawBitmap(bitmap, matrix, paint);

2 个答案:

答案 0 :(得分:34)

调整位图大小:

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

非常自我解释:只需输入原始的Bitmap对象和Bitmap的所需尺寸,此方法将返回新调整大小的Bitmap! 可能是,它对你有用。

答案 1 :(得分:0)

我正在使用上面的解决方案来调整位图的大小。但结果是部分图像丢失了。

这是我的代码。

 BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
            bmFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bmFactoryOptions.inMutable = true;
            bmFactoryOptions.inSampleSize = 2;
            Bitmap originalCameraBitmap = BitmapFactory.decodeByteArray(pData, 0, pData.length, bmFactoryOptions);
            rotatedBitmap = getResizedBitmap(originalCameraBitmap, cameraPreviewLayout.getHeight(), cameraPreviewLayout.getWidth() - preSizePriviewHight(), (int) rotationDegrees);

 public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, int angle) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        DeliverItApplication.getInstance().setImageCaptured(true);
        return resizedBitmap;
    }

这是图像的高度和宽度: 预览表面尺寸:352:288 在调整位图宽度之前:320高度:240 CameraPreviewLayout宽度:1080高度:1362 调整后的位图宽度:1022高度:1307