3
我有一段代碼,它所做的是找到圖像的顏色(或屏幕的一部分),如果RG和B的顏色大於127,則把1放在2D int數組的對應位置。這是我現在的細分市場,但顯然非常緩慢。有一個更好的方法嗎?有沒有更快的方式來獲取屏幕截圖中的顏色?
private void traceImage(){
try{
Robot r = new Robot();
b = new int[470][338];
for(int y = 597; y < 597+469; y++)
{
for(int x = 570; x < 570+337; x++)
{
if(r.getPixelColor(x,y).getRed() > 127 &&
r.getPixelColor(x,y).getGreen() > 127 &&
r.getPixelColor(x,y).getBlue() > 127)
{
b[y-597][x-570] = 1;
}
else
{
b[y-597][x-570] = 0;
}
}
}
}
catch(Exception ex){System.out.println(ex.toString());}
}
使用上面的值必須有更快的方法來做到這一點。 b
是int數組,它在此段中初始化。 r
是我用來查找屏幕上像素顏色的機器人。 x
和y
應該是自我解釋。
謝謝Mikera!這是我根據你的答案得到的最終結果:
private void traceActionPerformed(java.awt.event.ActionEvent evt) {
try{
Robot r = new Robot();
BufferedImage image = r.createScreenCapture(new Rectangle(597,570,470,337));
b = new int[image.getWidth()][image.getHeight()];
for(int y=0;y<image.getWidth();y++){
for(int x=0;x<image.getHeight();x++){
if(image.getRGB(y,x)==-1){
b[y][x]=0;
}
else{
b[y][x]=1;
}
}
}
System.out.println("Done");
}
catch(Exception ex){System.out.println(ex.toString());}
}
if if語句中的-1顯然會找到像我想要的黑色像素的值。