繁体   English   中英

在不改变原始纵横比的情况下将位图调整为 512x512

[英]Resize Bitmap to 512x512 Without changing original aspect ratio

我有一个创建的位图。 尺寸不具体。 有时 120x60 、 129x800 、 851x784。 它没有特定的值......我想让这些位图始终调整为 512x512,但不改变原始图像的纵横比。 而且没有裁剪。 新图像必须有 512x512 的画布,原始图像必须居中,没有任何裁剪。

我正在使用此功能调整位图大小,但它使图像非常糟糕,因为图像拟合 X 和 Y 。 我不希望图像同时适合 x 和 y 适合其中之一并保持其纵横比。

 public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        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);
        bm.recycle();
        return resizedBitmap;
    }

我拥有的;

在此处输入图片说明

我想要的是;

在此处输入图片说明

好的,您真的很亲近。 我目前无法测试,但是基本上需要更改的是

1)您需要对X和Y应用相同的比例尺,因此需要选择较小的比例尺(如果不可行,请尝试较大的比例尺)。

matrix.postScale(Math.min(scaleWidth, scaleHeight), Math.min(scaleWidth, scaleHeight));

2)结果将是一个位图,其中至少一侧为512px大,另一侧较小。 因此,您需要添加填充以使该边适合512像素(即居中的左右,上/下)。 为此,您需要创建所需大小的新位图:

Bitmap outputimage = Bitmap.createBitmap(512,512, Bitmap.Config.ARGB_8888);

3),最后这取决于侧的resizedBitmap是你512x512像素需要绘制resizedBitmap在正确的位置outputImage

Canvas can = new Canvas(outputimage);
can.drawBitmap(resizedBitmap, (512 - resizedBitmap.getWidth()) / 2, (512 - resizedBitmap.getHeight()) / 2, null);

请注意,这里512 - resizedBitmap.getWidth()结果为0 ,因此在具有正确大小的一侧没有填充。

4)现在返回outputImage

这是 Kotlin 中的一个简化,它使用矩阵进行缩放和平移,跳过中间位图。

请注意,它还将新像素的背景颜色设置为白色,这是我的图像管道所需要的。 如果您不需要它,请随意删除它。

fun resizedBitmapWithPadding(bitmap: Bitmap, newWidth: Int, newHeight: Int) : Bitmap {
    val scale = min(newWidth.toFloat() / bitmap.width, newHeight.toFloat() / bitmap.height)
    val scaledWidth = scale * bitmap.width
    val scaledHeight = scale * bitmap.height

    val matrix = Matrix()
    matrix.postScale(scale, scale)
    matrix.postTranslate(
        (newWidth - scaledWidth) / 2f,
        (newHeight - scaledHeight) / 2f
    )

    val outputBitmap = Bitmap.createBitmap(newWidth, newHeight, bitmap.config)
    outputBitmap.eraseColor(Color.WHITE)
    
    Canvas(outputBitmap).drawBitmap(
        bitmap,
        matrix,
        null
    )

    return outputBitmap
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM