2011-12-15 113 views
2

我編寫了一些類似於繪畫的東西。我有JPanel,我可以借鑑它。我只使用黑線。我想將它轉換爲二進制數組,其中1是像素爲黑色時,0爲白色時(背景)。這是可能的?這個怎麼做?將JPanel轉換爲二進制數組

+0

http://stackoverflow.com/questions/113897/how-do-i-get-the-image-paint-paintcomponent-generates應該幫助你起步 – Robin 2011-12-15 19:11:10

回答

2

簡而言之,創建一個尺寸與您的JPanel和paint the panel相同的BufferedImage。然後,您可以遍歷圖像柵格以獲取與黑色和白色相對應的像素顏色值序列。例如

// 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... 
    } 
    } 
} 
+0

參見[ComponentImageCapture.java] (http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992)。 – 2011-12-15 19:35:35

相關問題