如何在Java中为图像添加边框



边界需要由给定图像的最近像素组成,我在网上看到了一些代码,并得出了以下结果。我做错了什么?我是java的新手,不允许使用任何方法。

/**
* TODO Method to be done. It contains some code that has to be changed
* 
* @param enlargeFactorPercentage the border in percentage
* @param dimAvg                  the radius in pixels to get the average colour
*                                of each pixel for the border
* 
* @return a new image extended with borders
*/
public static BufferedImage addBorders(BufferedImage image, int enlargeFactorPercentage, int dimAvg) {
// TODO method to be done
int height = image.getHeight();
int width = image.getWidth();
System.out.println("Image height = " + height);
System.out.println("Image width = " + width);
// create new image
BufferedImage bi = new BufferedImage(width, height, image.getType());
// copy image
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixelRGB = image.getRGB(x, y);
bi.setRGB(x, y, pixelRGB);
}
}
// draw top and bottom borders
// draw left and right borders
// draw corners
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixelRGB = image.getRGB(x, y);
for (enlargeFactorPercentage = 0; enlargeFactorPercentage < 10; enlargeFactorPercentage++){
bi.setRGB(width, enlargeFactorPercentage, pixelRGB * dimAvg);
bi.setRGB(enlargeFactorPercentage, height, pixelRGB * dimAvg);
}
}
}
return bi;

我不允许使用任何方法。

这是什么意思?如果不能使用API中的方法,那么如何编写代码?

int enlargeFactorPercentage

那是干什么的?对我来说,放大意味着要做得更大。所以,如果你有一个因子10,你的图像是(100100(,那么新的图像将是(110110(,这意味着边界将是5个像素?

您的代码正在创建与原始图像大小相同的BufferedImage。那么,这是否意味着你将边界设为5个像素,并从原始图像中截取5个像素?

如果没有适当的要求,我们就无能为力。

@返回用边界扩展的新图像

由于您也有一条评论说"扩展",我假设您的要求是返回更大的图像。

所以我使用的解决方案是:

  1. 以增大的大小创建BufferedImage
  2. 从BufferImage获取Graphics2D对象
  3. 使用Graphics2D.fillRect(….)方法用所需的边框颜色填充整个BufferedImage
  4. 使用CCD_ 2方法将原始图像绘制到放大的BufferedImage上

大家好,欢迎来到stackoverflow!

不确定"不允许使用方法"是什么意思。如果没有方法,你甚至无法运行程序,因为public static void main(String[] args)的"东西"是一个方法(主方法(,你需要它,因为它是程序的起点。。。

但要回答您的问题:你必须加载你的图像。一种可能性是使用ImageIO。然后创建一个2D图形对象,然后可以使用drawRectangle((创建一个边界矩形:

BufferedImage bi = //load image
Graphics2D g = bi.getGraphics();
g.drawRectangle(0, 0, bi.getHeight(), bi.getWidth());

这个简短的代码只是一个提示。尝试并阅读Bufferedimage中的文档请参阅此处和Graphics2D

编辑:请注意,这不是很正确。使用上面的代码,您可以从图像中透支外部像素线。如果你不想剪切的任何像素,那么你必须放大它并用bi.getHeight()+2bi.getWidth()+2绘制+2,因为在图像的每一侧都需要多一个像素。

最新更新