【问题标题】:Java - How to pad and resize image without cropping?Java - 如何在不裁剪的情况下填充和调整图像大小?
【发布时间】:2019-05-10 08:55:02
【问题描述】:

我需要将很多图像的大小从比例 (2:3) 调整为 (3:4)。

图片目前为 800px x 1200px。我最终需要它们是 600px x 800px 而不进行任何裁剪。

我可以知道哪些库可供我在 Java 中进行填充和调整大小而不进行裁剪吗?

【问题讨论】:

  • Image.getScaledInstance(...)
  • “我可以知道哪些库可供我在 Java 中进行填充和调整大小而不进行裁剪吗?” 我已投票决定关闭它,但简短的回答是 AWT ( java.awt & java.awt.image 包中的类)。
  • 您好,谢谢您的回复,您的方法我试过了。当调整为较小的图像时,图像会被挤压,从而使图像中的人变得更瘦。当调整到更大的图像时,图像会被拉伸,从而使图像中的人变得更胖。

标签: java image resize


【解决方案1】:

从您当前的图片(假设为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);

【讨论】:

  • 您好,谢谢您的回复,您的方法我试过了。当调整为较小的图像时,图像会被挤压,从而使图像中的人变得更瘦。当调整为更大的图像时,图像会被拉伸,从而使图像中的人变得更胖。
  • @SomeoneInNeedOfHelp 使用比例因子尝试我的代码,因为您可能会使用不成比例的尺寸,如果您不保持比例,它看起来就不会是正常的
  • 我需要将很多图像从比例 (2:3) 调整为 (3:4)。您的代码是调整图像大小并保持比例纵横比。我需要填充图像以更改比例方面。
  • @SomeoneInNeedOfHelp 找到了。使用适用于两种填充、尊重比例和所需大小的方法进行编辑;)
【解决方案2】:

我认为 ffmpeg 可以帮助您对图像做任何事情。 例如Use ffmpeg to resize image

  1. 您可以将 ffmpeg 二进制文件保存在某个 conf 文件夹中。
  2. 为 ffmpeg 命令创建 sh 脚本。
  3. 使用(Apache Commons exec 库)中的命令行来运行脚本。

【讨论】:

    【解决方案3】:

    使用以下代码设法做到这一点: '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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多