繁体   English   中英

调整 Java BufferedImage 的大小,保持纵横比并填充背景

[英]Resize Java BufferedImage keeping aspect ratio and fill with background

我正在使用 Java 来存储和修改 .jpg 图像(不是 Android 或 Swing)。 如果新尺寸与原始图像不成比例,我想转换具有新尺寸的图像以保持纵横比并用白色填充背景。

 BufferedImage image = /*Here i read from disk and load the image */;
 image = resizeImage(image,  newWidth, newHeight);
 ImageIO.write(image, extension, new File(filename + "_" + page + "." + extension));

我试图实现的功能是 resizeImage:在示例中调整图像大小,但它不保持纵横比。

  private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }

我认为一张图片将更能说明我的要求: 函数图像行为

如果原始图像是 200x200 并且被要求将大小调整为 400x300,则结果应该是带有白边的图片,并且原始图片的大小在内部进行了调整。 在此示例中应为 300x300。

问题不在于如何调整大小,而在于如何用白色填充剩余的图像,并将原始调整大小的图像放在它的中心。

这段代码对我有用:

private static BufferedImage resizeImage(BufferedImage originalImage, int newWidth, int newHeight) {
    BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
    Graphics2D graphics = resizedImage.createGraphics();
    graphics.setColor(Color.WHITE);
    // fill the entire picture with white
    graphics.fillRect(0, 0, newWidth, newHeight);
    int maxWidth = 0;
    int maxHeight = 0;
    // go along the width and height in increments of 1 until one value is equal to the specified resize value
    while (maxWidth <= newWidth && maxHeight <= newHeight)
    {
        ++maxWidth;
        ++maxHeight;
    }
    // calculate the x value with which the original image is centred
    int centerX = (resizedImage.getWidth() - maxWidth) / 2;
    // calculate the y value with which the original image is centred
    int centerY = (resizedImage.getHeight() - maxHeight) / 2;
    // draw the original image
    graphics.drawImage(originalImage, centerX, centerY, maxWidth, maxHeight, null);
    graphics.dispose();
    return resizedImage;
}

前: 在此处输入图像描述

后: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM