我编写了类似涂料的东西。我有JPanel,我可以画它。我只使用黑线。我想将它转换为二进制数组,其中1表示像素为黑色,0表示为白色(背景)。这是可能的?怎么做?
答案 0 :(得分:2)
简而言之,为图片创建与JPanel和BufferedImage
尺寸相同的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...
}
}
}