簡體   English   中英

Java-如何在不裁剪的情況下填充圖像並調整其大小?

[英]Java - How to pad and resize image without cropping?

我需要從(2:3)到(3:4)的比例調整很多圖像的大小。

圖片目前為800像素x 1200像素。 我需要它們最終為600像素x 800像素,而無需裁剪。

我可以知道哪些庫可供我進行填充和調整大小而無需在Java中裁剪嗎?

從當前的Image(假設一個java.awt.Image )中,您可以使用:

這些步驟:

  • 計算比率在widthheight
  • 取決於其值(填充寬度或填充高度)
    • 計算widthheight以獲得縮放的圖像
    • 計算所需的填充
  • 將圖像寫在合適的位置
static BufferedImage pad(BufferedImage image, double width, double height, Color pad) {
    double ratioW = image.getWidth() / width;
    double ratioH = image.getHeight() / height;
    double newWidth = width, newHeight = height;
    int fitW = 0, fitH = 0;
    BufferedImage resultImage;
    Image resize;

    //padding width
    if (ratioW < ratioH) {
        newWidth = image.getWidth() / ratioH;
        newHeight = image.getHeight() / ratioH;
        fitW = (int) ((width - newWidth) / 2.0);

    }//padding height
    else if (ratioH < ratioW) {
        newWidth = image.getWidth() / ratioW;
        newHeight = image.getHeight() / ratioW;
        fitH = (int) ((height - newHeight) / 2.0);
    }

    resize = image.getScaledInstance((int) newWidth, (int) newHeight, Image.SCALE_SMOOTH);
    resultImage = new BufferedImage((int) width, (int) height, image.getType());
    Graphics g = resultImage.getGraphics();
    g.setColor(pad);
    g.fillRect(0, 0, (int) width, (int) height);
    g.drawImage(resize, fitW, fitH, null);
    g.dispose();

    return resultImage;
}

用作

BufferedImage image = ...;
BufferedImage result = pad(image, 600, 800, Color.white);

我認為ffmpeg可以幫助您處理圖像。 例如, 使用ffmpeg調整圖像大小

  1. 您可以將ffmpeg二進制文件保存在某些conf文件夾中。
  2. 為ffmpeg命令創建sh腳本。
  3. 從(Apache Commons exec庫)使用CommandLine運行腳本。

使用以下代碼成功做到了這一點:“ w”是您需要在每一側填充的數量。

BufferedImage newImage = new BufferedImage(image.getWidth()+2*w, image.getHeight(), 
image.getType());

Graphics g = newImage.getGraphics();

g.setColor(Color.white);
g.fillRect(0,0,image.getWidth()+2*w,image.getHeight());
g.drawImage(image, w, 0, null);
g.dispose();

暫無
暫無

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

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