[英]How can I resize a rectangular image to a square image while maintaining aspect ratio in Java?
我需要將矩形圖像(400x600)調整為方形圖像(600x600),同時保持原始圖像的縱橫比。 新添加的像素需要是透明的。 像這樣。
我在 java 或 kotlin 代碼中需要它。 但是,如果這不可能,那么我不介意任何其他語言的解決方案。
在過去的 3 天里,我一直無法找到合適的解決方案。 所有類似的問題都沒有幫助,因為它們在保持縱橫比的同時處理放大或縮小高度和寬度。 我只需要增加寬度。
試試這個代碼:
public static BufferedImage increaseSize(BufferedImage input){
//TODO: Maybe validate the input.
//Create a new image of 600*600 pixels
BufferedImage output=new BufferedImage(600,600,BufferedImage.TYPE_4BYTE_ABGR);
//Get the graphics object to draw onto the image
Graphics g=output.getGraphics();
//This is a transparent color
Color transparent=new Color(0f,0f,0f,0f);
//Set the transparent color as drawing color
g.setColor(transparent);
//Make the whole image transparent
g.fillRect(0,0,600,600);
//Draw the input image at P(100/0), so there are transparent margins
g.drawImage(input,100,0,null);
//Release the Graphics object
g.dispose();
//Return the 600*600 image
return output;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.