首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >调整Java BufferedImage的大小,保持高宽比并填充背景

调整Java BufferedImage的大小,保持高宽比并填充背景
EN

Stack Overflow用户
提问于 2022-06-10 16:38:20
回答 1查看 182关注 0票数 0

我正在使用Java存储和修改.jpg图像(不是安卓或Swing)。我想转换一个新尺寸的图像,保持高宽比,如果新尺寸与原始图像不成比例,则用白色填充背景。

代码语言:javascript
运行
复制
 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:在示例中调整图像大小,但它不保持高宽比。

代码语言:javascript
运行
复制
  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。

问题不是如何调整大小,而是如何用白色填充剩馀的图像,以及中心的原始大小调整的图像。

EN

Stack Overflow用户

回答已采纳

发布于 2022-06-10 18:36:36

这段代码适用于我:

代码语言:javascript
运行
复制
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;
}

在此之前:

之后:

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72577436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档