3 回答

TA貢獻1895條經驗 獲得超3個贊
private static final int MAX_FEAT_IMAGE_WIDTH = 600;
private static final int MAX_FEAT_IMAGE_WIDTH = 600;
double featImageWidth = originalImage.getWidth();
double featImageHeight = originalImage.getHeight();
// Sanity check on the input (division by zero, infinity):
if (featImageWidth <= 1 || featImageHeight <= 1) {
throw new IllegalArgumentException("..." + featureImage);
}
// The scaling factors to reach to maxima on width and height:
double xScale = MAX_FEAT_IMAGE_WIDTH / featImageWidth;
double yScale = MAX_FEAT_IMAGE_HEIGHT / featImageHeight;
// Proportional (scale width and height by the same factor):
double scale = Math.min(xScale, yScale);
// (Possibly) Do not enlarge:
scale = Math.min(1.0, scale);
int finalWidth = Math.min((int) Math.round(scale * featImageWidth), MAX_FEAT_IMAGE_WIDTH);
int finalHeight = Math.min((int) Math.round(scale * featImageHeigth), MAX_FEAT_IMAGE_HEIGHT);
如您所見,我扭轉了兩件事,以保持比例縮放。在心理上使用比率 ( /) 而不是比例因子 ( *) 似乎更難。
分別確定寬度和高度的縮放比例讓我們選擇最小縮放比例。
一個人也可以決定不放大小圖片。

TA貢獻1842條經驗 獲得超21個贊
您只考慮方向(ratio< 1 表示垂直,否則為水平或正方形)。這還不夠;您必須考慮目標寬度/高度:
int sw = originalImage.getWidth();
int sh = originalImage.getHeight();
int swdh = sw * maxFeatImageHeight;
int shdw = sh * maxFeatImageWidth;
if (swdh < shdw) {
finalWidth = swdh / sh;
finalHeight = maxFeatImageHeight;
} else {
finalWidth = maxFeatImageWidth;
finalHeight = shdw / sw;
}
更新:
好的,讓我們從天平開始:
double xScale = maxFeatImageWidth/featImageWidth;
double yScale = maxFeatImageHeight/featImageHeight;
你可以寫:
在 yScale < xScale 的情況下,我們需要使用 yScale:
finalWidth = featImageWidth*yScale = featImageWidth*maxFeatImageHeight/featImageHeight;
finalHeight = maxFeatImageHeight;
否則,我們可以使用 xScale:
finalWidth = maxFeatImageWidth;
finalHeight = featImageHeight*xScale = featImageHeight*maxFeatImageWidth/featImageWidth;
由于所有寬度和高度都 > 0,因此 yScale < xScale 的結果與:
featImageWidth*featImageHeight*yScale < featImageWidth*featImageHeight*xScale
所以
featImageWidth*featImageHeight*maxFeatImageHeight/featImageHeight < featImageWidth*featImageHeight*maxFeatImageWidth/featImageWidth
和
maxFeatImageHeight*featImageWidth < maxFeatImageHeight*featImageWidth
我將這兩個值保存為 swdh 和 shdw,因為它們可以在以后重復使用。
int它避免了從到double和從double到的轉換int。

TA貢獻1780條經驗 獲得超1個贊
很可能你應該知道要調整大小的圖像的大小,然后基于該值 if 和 else 語句應該起作用,然后調用調整大小函數你將能夠調整它的大小。我希望這有幫助。并且當您調整大小時,請確保您也能夠按照用戶定義的方式減少像素。
添加回答
舉報