2010-11-11 117 views
1

當鼠標懸停指向照片的一個位置時,如何識別顏色?Java如何識別照片顏色?

BufferedImage image = new BufferedImage("blueball.jpg"); 
Project() { 
    jFrame.setSize(new Dimension(500, 320)); 
    jFrame.getContentPane().setLayout(null); 
    colorLabelText.setBounds(new Rectangle(310, 210, 50, 30)); 
    colorLabelText.setText("Color :"); 
    colorLabel.setBounds(new Rectangle(370, 210, 100, 30)); 
    photoLabel.setBounds(new Rectangle(20, 20, 220, 250)); 
    photoLabel.addMouseListener(new RecognizeColorActionListener()); 
    jFrame.getContentPane().add(photoLabel); 
    jFrame.getContentPane().add(colorLabelText); 
    jFrame.getContentPane().add(colorLabel); 
    jFrame.setVisible(true); 
} 


    class RecognizeColorActionListener implements MouseListener { 
    @Override 
    public void mouseClicked(MouseEvent e) { 
     int x = e.getX(); 
         int y = e.getY(); 
         int imgx = image.getMinX(); 
         int imgy = image.getMinY(); 
         int c = image.getRGB(x - imgx, y - imgy); 

發生錯誤java.lang.ArrayIndexOutOfBoundsException:協調出界!

+0

如何顯示圖像? – fish 2010-11-11 17:13:42

+0

我在標籤中顯示標籤位置是photoLabel.setBounds(new Rectangle(20,20,220,250)); – user236501 2010-11-11 17:34:10

+0

它有沒有工作,例如在左上角?你是否從photoLabel的左上角繪製圖像? image.getWidth(),image.getHeight()給你什麼? – fish 2010-11-12 06:42:30

回答

7

問題是鼠標的X和Y座標不對應於圖像的X和Y座標。將其更改爲如下所示:

int x = e.getX(); 
int y = e.getY(); 
int imgx = image.getX(); 
int imgy = image.getY(); 
int c = image.getRGB(x - imgx, y - imgy); 

請不要引用我完全的語法,但這是基本的想法。

+0

謝謝,它是getMinX(),getMinY()?我仍然得到這個錯誤java.lang.ArrayIndexOutOfBoundsException:座標超出界限! – user236501 2010-11-11 16:28:31

+0

我不確定,因爲我現在在機器上沒有Java開發環境。我所描述的是這個問題,但是你需要玩弄一些事情才能完全正確。 – riwalk 2010-11-11 16:30:32

+0

也許略有不同導致我的圖像被緩衝圖片 – user236501 2010-11-12 03:12:05