如何计算图像的新高度和宽度以适应预定义的高度和宽度,而不影响java中的图像真实宽高比?

2 java

我想缩放图像以适应某些预定义的大小而不影响实际图像的宽高比.

我们在java中有任何预定义的算法吗?

更新:

像这样调整大小.输出是相同的图像,但尺寸较小.外框只是一个标记.

在此输入图像描述

cor*_*iKa 6

你要在宽度或高度上都有空隙......问题在于找出哪个.

double widthRatio = realWidth / definedWidth;
double heightRatio = realHeight / definedHeight;

if(heightRatio > widthRatio) {
    // scale image to match the height, and let the width have the gaps

} else {
    // scale image to match the width, and let the height have the gaps

}
Run Code Online (Sandbox Code Playgroud)

  • 如果你的框架宽度是800,并且大小的图像宽度是300,你有500像素的空白,所以要使你的图像居中,让它在任何一边250 (2认同)