我编写了类似绘画的程序。我有 JPanel,我可以在上面画画。我只使用黑线。我想将它转换为二进制数组,其中 1 表示像素为黑色,0 表示白色(背景)。这是可能的?如何做到这一点?
最佳答案
简而言之,创建一个 BufferedImage
与您的 JPanel 和 paint the panel 具有相同的尺寸到图像。然后您可以遍历图像光栅以获得对应于黑色和白色的像素颜色值序列。例如
// Paint the JPanel to a BufferedImage.
Dimension size = jpanel.getSize();
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = BufferedImage(size.width, size.height, imageType);
Graphics2D g2d = image.createGraphics();
jpanel.paint(g2);
// Now iterate the image in row-major order to test its pixel colors.
for (int y=0; y<size.height; y++) {
for (int x=0; ix<size.width; x++) {
int pixel = image.getRGB(x, y);
if (pixel == 0xFF000000) {
// Black (assuming no transparency).
} else if (pixel == 0xFFFFFFFF) {
// White (assuming no transparency).
} else {
// Some other color...
}
}
}
关于java - 将 JPanel 转换为二进制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8525291/