user236501
user236501

Reputation: 8648

Java How can I recognize a photo color?

How can I recognise the color when i mouseover point to one postition of the photo?

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); 

Error occurs java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!

Upvotes: 1

Views: 498

Answers (1)

riwalk
riwalk

Reputation: 14223

The problem is the the X and Y coordinates of the mouse do not correspond to the X and Y coordinates of the image. Change it to something like this:

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

Don't quote me exactly on the syntax, but that is the basic idea.

Upvotes: 7

Related Questions