[英]Java > Drawing multiple rectangles on an existing image
我正在根据像素比较两个图像,并且需要在不匹配的像素值周围绘制一个矩形。 它正确地在不匹配的第一个像素周围绘制了w矩形,但在病区上却没有。
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();
}
}
}
}
g.drawImage(temp, 0, 0, null);
将覆盖以前绘制的所有内容,而不是循环中的好主意 g.dispose
可能会阻止g.dispose
将任何内容更新/绘制到上下文中。 您应该只在完成后才真正调用它 作为快速测试,我将以下图像用作输入...
跑过去...
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));
哪个输出...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.