以下全部发生在服务器端。我想缩放图像如下。
图像应缩放以适合预定义的尺寸。图像应缩放以适合边界矩形。我知道如何使用像 imageScalr 这样的 Java 库来缩放图像。缩放后,图像应在目标尺寸矩形中绘制,图像未填充目标矩形的位置应绘制为红色,如下图所示:
如何将图像绘制到目标矩形中并用红色填充没有图像的区域?
最佳答案
创建一个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了解更多详情
关于java - 将图像大小调整为定义的尺寸并将未使用的区域涂成红色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466541/