java - 将图像大小调整为定义的尺寸并将未使用的区域涂成红色?

标签 java groovy image-resizing image-scaling

以下全部发生在服务器端。我想缩放图像如下。

enter image description here

图像应缩放以适合预定义的尺寸。图像应缩放以适合边界矩形。我知道如何使用像 imageScalr 这样的 Java 库来缩放图像。缩放后,图像应在目标尺寸矩形中绘制,图像未填充目标矩形的位置应绘制为红色,如下图所示:

enter image description here

如何将图像绘制到目标矩形中并用红色填充没有图像的区域?

最佳答案

创建一个BufferedImage,它是所需区域的框的边界

// 100x100 is the desired bounding box of the scaled area
// Change this for the actual area you want to use
BufferedImage scaledArea = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

使用 BufferedImageGraphics 上下文,用所需的颜色填充图像

Graphics2D g2d = scaledArea.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, 100, 100);

将缩放后的图像绘制到此图像中...

// 100x100 is the desired bounding box of the scaled area
// Change this for the actual area you want to use
int x = (100 - scaled.getWidth()) / 2;
int y = (100 - scaled.getHeight()) / 2;
g2d.drawImage(scaled, x, y, null);
g2d.dispose();

然后你可以使用ImageIO.write来保存结果

enter image description here

看看2D GraphicsWriting/Saving an Image了解更多详情

关于java - 将图像大小调整为定义的尺寸并将未使用的区域涂成红色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466541/

相关文章:

java - 如何访问 Java 中的私有(private)类成员?

java - maven central 是否希望共享源 URL?

队列集合的 Java 数据结构

java - GroovyScriptEngine 在 Web 容器中定位资源

javascript - 仅调整垂直图像的大小

java - 更改 GET 页面请求上的数据(处理预加载请求)

grails - Groovy Grails-存储对象以供后续请求

groovy - jenkins 扩展参数插件 groovy 脚本

image-processing - 裁剪、缩放、调整大小和更改图像的纵横比之间的区别?

ios - 图像在 iPhone 8 和 8 plus 上呈现不同