【发布时间】:2020-07-11 17:02:32
【问题描述】:
我需要将矩形图像 (400x600) 调整为方形图像 (600x600),同时保持原始图像的纵横比。新添加的像素需要是透明的。赞this.
我需要它在 java 或 kotlin 代码中。但是,如果这不可能,那么我不介意使用任何其他语言的解决方案。
在过去的 3 天里,我一直未能找到合适的解决方案。所有类似的问题都没有帮助,因为它们在保持纵横比的同时处理高度和宽度的放大或缩小。我只需要增加宽度。
【问题讨论】:
我需要将矩形图像 (400x600) 调整为方形图像 (600x600),同时保持原始图像的纵横比。新添加的像素需要是透明的。赞this.
我需要它在 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;
}
【讨论】: