以下所有内容都发生在服务器端。我想像下面那样缩放图像。
应缩放图像以适合预定义的尺寸。图像应缩放以适合边界矩形。我知道如何使用像imageScalr这样的Java库来扩展图像。缩放后,图像应绘制在目标尺寸矩形中,图像未填充目标矩形的位置应涂成红色,如下图所示:
如何将图像绘制到目标矩形中并填充没有红色图像的区域?
答案 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
保存结果
看看2D Graphics和 Writing/Saving an Image了解更多详情