将图像调整为已定义的尺寸并将未使用的区域绘制为红色?

时间:2015-07-17 00:09:17

标签: java groovy image-resizing image-scaling

以下所有内容都发生在服务器端。我想像下面那样缩放图像。

enter image description here

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

enter image description here

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

1 个答案:

答案 0 :(得分:2)

创建一个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);

使用BufferedImage' Graphics上下文,用所需颜色填充图片

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了解更多详情