我正在尝试将 JPanel 的内容转换为 BufferedImage。环顾四周后,我得到了这段代码。
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
this.paint(g);
我使用以下代码迭代图像,查找黑色像素。
for(int i = 0; i < image.getWidth(); i++){
for(int j = 0; j < image.getHeight(); j++){
Color tempColor = new Color(image.getRGB(i, j));
if(tempColor == Color.BLACK){
System.out.println(tempColor); //Debugging
}
}
}
JPanel 包含许多使用 Color.BLACK 绘制的像素(所以是的,它们是黑色的),尽管运行此代码时,它从不打印调试行。
我相信我的代码中的错误与我将 JPanel 的内容复制到 BufferedImage 的方式有关,我似乎无法弄清楚我做错了什么。非常感谢任何帮助,谢谢。
最佳答案
您在测试 tempColor == Color.BLACK
时正在执行引用相等测试。但是new Color(…)
始终创建一个新对象,该对象永远不能与预定义的对象相同 Color.BLACK
例如,==
检查将始终是 false
.
使用equals
或者干脆省略处理 Color
根本没有对象,只需检查是否 image.getRGB(i, j) == 0
或者如果您不想使用零表示黑色,您也可以使用 image.getRGB(i, j) == Color.BLACK.getRGB()
关于java - JPanel 到 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33641563/