【问题标题】:How can I resize a rectangular image to a square image while maintaining aspect ratio in Java?如何在 Java 中保持纵横比的同时将矩形图像调整为方形图像?
【发布时间】:2020-07-11 17:02:32
【问题描述】:

我需要将矩形图像 (400x600) 调整为方形图像 (600x600),同时保持原始图像的纵横比。新添加的像素需要是透明的。赞this.

我需要它在 java 或 kotlin 代码中。但是,如果这不可能,那么我不介意使用任何其他语言的解决方案。

在过去的 3 天里,我一直未能找到合适的解决方案。所有类似的问题都没有帮助,因为它们在保持纵横比的同时处理高度和宽度的放大或缩小。我只需要增加宽度。

【问题讨论】:

标签: java image kotlin rescale


【解决方案1】:

试试这个代码:

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;
}

这里是一个例子: 左边是之前的图片,右边是转换后的效果。

【讨论】:

  • 好答案。 Kotlin 版本将非常相似。 (当然,在任何一种情况下,对于生产代码,您可能会传入新尺寸而不是硬编码,复制现有图像的类型,计算在新图像中绘制现有图像的位置,并且可能会出现一些错误陷阱。但我相信 OP 意识到了这一点!这个答案很好地说明了要点。)
  • 非常感谢。只需稍加编辑即可完美运行
猜你喜欢
  • 2018-02-24
  • 2018-11-04
  • 2015-04-18
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2021-05-25
相关资源
最近更新 更多