簡體   English   中英

縮放圖像保持縱橫比不低於目標

[英]scale an image keeping the aspect ratio without falling below the targets

我想知道是否有人可以幫助我使用數學/偽代碼/java代碼將圖像縮放到目標尺寸。 要求是保持縱橫比,但在 x 和 y 尺度上都不能低於目標尺寸。 最終計算的尺寸可以大於請求的目標,但它必須是最接近目標的尺寸。

示例:我有一個 200x100 的圖像。 它需要按比例縮小到 30x10 的目標尺寸。 我需要找到保持原點縱橫比的最小尺寸,其中 x 和 y 比例至少是目標中指定的比例。 在我們的示例中,20x10 並不好,因為 x 比例低於目標(即 30)。 最接近的是 30x15

謝謝你。

targetRatio = targetWidth / targetHeight;
sourceRatio = sourceWidth / sourceHeight;
if(sourceRatio >= targetRatio){ // source is wider than target in proportion
    requiredWidth = targetWidth;
    requiredHeight = requiredWidth / sourceRatio;      
}else{ // source is higher than target in proportion
    requiredHeight = targetHeight;
    requiredWidth = requiredHeight * sourceRatio;      
} 

這樣你的最終圖像:

  • 始終適合目標內部而不被裁剪。

  • 保持其原始縱橫比。

  • 並且始終具有與目標完全匹配的寬度或高度(或兩者)。

好吧,在您的示例中,您已經使用了您正在尋找的算法。 我將使用您給出的示例。

Original          Target
200 x 100   ->    30 x 10

1. You take the bigger value of the target dimensions (in our case 30)
2. Check if its smaller than the corresponding original width or height
  2.1 If its smaller define this as the new width (So 30 is the new width)
  2.2 If its not smaller check the other part
3. Now we have to calculate the height which is simply the (30/200)*100

So as result you get like you wrote: 30 x 15

希望這很清楚:)

在編碼部分,您可以使用BufferedImage並簡單地創建一個具有正確比例值的新 BufferedImage 。

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0); // <-- Here you should use the calculated scale factors
AffineTransformOp scaleOp = 
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM