我正在尝试创建一种方法,将边框添加到 BufferedImage,其中边框厚度和边框颜色都可以通过该方法的参数进行配置。
边框厚度将是一个非负整数(0、1、2 等),对应于图像周边内所有四个边的边框厚度应有多少像素。
边框颜色是一个长度为3的整数数组,对应边框应为的RGB颜色值。
这就是图像的样子,边框厚度为 10,RGB 值为 235、64、52:
这是我到目前为止的代码,但我在下一步做什么方面遇到了困难。
我将非常感谢任何帮助。我还意识到我可以使用 Java 的图形工具在图像之上进行编辑,但我正在尝试编辑图像本身而不是创建任何类型的覆盖。
public static void applyBorder(BufferedImage img, int borderThickness, int[] borderColor) {
int width = img.getWidth();
int height = img.getHeight();
int[] pixels = img.getRGB(0, 0, width, height, null, 0, width);
for (int i = 0; i < pixels.length; i++){
int p = pixels[i];
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
}
}
您可以使用
Graphics
中的 Graphics2D
/BufferedImage
对象简单地在图像周围创建边框。例如:
public BufferedImage addBorder(BufferedImage img, int borderThickness, Color borderColor) {
int width = img.getWidth();
int height = img.getHeight();
// create a new image, the same size as the old
BufferedImage newImg = new BufferedImage(width, height, img.getType());
// extract the Graphics2D object
Graphics2D g = newImg.createGraphics();
// draw the original image with it
g.drawImage(img, 0, 0, null);
// then draw the border
g.setColor(borderColor);
g.setStroke(new BasicStroke(borderThickness));
g.drawRect(0, 0, width, height);
// conserve resources
g.dispose();
return newImg;
}