Java>在现有图像上绘制多个矩形

时间:2017-06-09 10:25:37

标签: java awt

我正在根据像素比较两个图像,需要围绕不匹配的像素值绘制一个矩形。它正确地绘制了第一个不匹配的像素周围的矩形,但在病房里并没有。

for (int row = 0; row < height; row++) {  
    for (int col = 0; col < width; col++) {  
        result[row][col] = img1.getRGB(col, row);  
        result1[row][col] = img2.getRGB(col, row);  
        if(result[row][col] != result1[row][col]){  
         try {  
            g.drawImage(temp, 0, 0, null);  
            g.setColor(Color.red);  
            g.setStroke(new BasicStroke(2.0F));  
            g.drawRect(col-5, row-12, 35, 35);  
            } finally {  
            g.dispose();  
            }  
        }  
    }  
}  

1 个答案:

答案 0 :(得分:1)

  • g.drawImage(temp, 0, 0, null);将绘制以前绘制的任何内容,而不是环路中的好主意
  • g.dispose可以防止将来更新/绘制任何内容。你完全应该在完成后才打电话

作为快速测试,我将以下图像作为输入...

img1 img2

通过......

BufferedImage img1 = ImageIO.read(new File("..."));
BufferedImage img2 = ImageIO.read(new File("..."));

int width = img1.getWidth();
int height = img1.getHeight();

BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = temp.createGraphics();
g.drawImage(img1, 0, 0, null);

for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
        int result = img1.getRGB(col, row);
        int result1 = img2.getRGB(col, row);
        if (result != result1) {
                g.setColor(Color.red);
                g.setStroke(new BasicStroke(2.0F));
                g.drawRect(col - 5, row - 12, 35, 35);
        }
    }
}
g.dispose();

JOptionPane.showMessageDialog(null, new ImageIcon(temp));

哪个输出......

Result