Pixel Grabber in Java

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
wearymemory
Chaos Rift Junior
Chaos Rift Junior
Posts: 209
Joined: Thu Feb 12, 2009 8:46 pm

Pixel Grabber in Java

Post by wearymemory »

No longer will you have to press the Prt Scr button, open up Paint, press Ctrl-V, Click on the Magnifier, then on the picture, then click on the Pick Color tool, then on the pixel you want, and then expand the Colors menu, and then on the Edit Colors menu item, and then click the Define Custom Colors >> button, just so you can figure out the RGB values of that sweet color you saw earlier once you try this baby out.

A simple example (and a somewhat useful program), that includes: using the java.awt.Robot class to grab colors from the screen, using the system look and feel, changing the opacity of a window, and other neat tricks. This program wasn't necessarily made to be useful, but feel free to try it out.

Examples:

Image

Image

Attached is the assembled JAR file inside of a ZIP archive.

PixelGrabber.java

Code: Select all

package misc;

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.util.concurrent.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.event.*;

public class PixelGrabber extends JFrame {
    
    private static Robot robot;
    private static void initRobot() {
        try {
            robot = new Robot();
        } catch (AWTException ex) {
            Logger.getLogger(PixelGrabber.class.getName()).log(Level.SEVERE,
                    null, ex);
            System.exit(1);
        }
    }

    private static void setWindowOpacity(Window window, float f) {
        try {
            Class<?> awtUtilitiesClass =
                    Class.forName("com.sun.awt.AWTUtilities");
            Method mSetWindowOpacity =
                    awtUtilitiesClass.getMethod("setWindowOpacity",
                    Window.class, float.class);
            mSetWindowOpacity.invoke(null, window, f);
        } catch (Exception ex) {
            Logger.getLogger(PixelGrabber.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }

    public PixelGrabber() {
        if (robot == null)
            initRobot();
        initComponents();
        Executors.newSingleThreadExecutor().execute(new PixelGrabberThread());
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        menuBar = new JMenuBar();
        pixelGrabberMenu = new JMenu("Pixel Grabber");
        pixelGrabberToggle = new JCheckBoxMenuItem() {
            @Override public String getText() {
                return "Grabber (" + (isSelected() ? "On" : "Off") + ")";
            }
            @Override public KeyStroke getAccelerator() {
                return KeyStroke.getKeyStroke("alt G");
            }
        };
        pixelGrabberMenu.add(pixelGrabberToggle);
        pixelGrabberMenu.addSeparator();
        opacityToggle = new JCheckBoxMenuItem() {
            @Override public String getText() {
                return "Opacity (" + (isSelected() ? "On" : "Off") + ")";
            }
            @Override public KeyStroke getAccelerator() {
                return KeyStroke.getKeyStroke("alt O");
            }
            @Override public void fireActionPerformed(ActionEvent e) {
                setWindowOpacity(PixelGrabber.this, isSelected() ? 1F : 0.75F);
            }
        };
        pixelGrabberMenu.add(opacityToggle);
        menuBar.add(pixelGrabberMenu);
        setJMenuBar(menuBar);

        redLabel = new JLabel("Red");
        greenLabel = new JLabel("Green");
        blueLabel = new JLabel("Blue");
        previewLabel = new JLabel("Preview");

        redSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 255, 1));
        greenSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 255, 1));
        blueSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 255, 1));

        ChangeListener changeListener = new ColorSpinnerChangeListener();
        redSpinner.addChangeListener(changeListener);
        greenSpinner.addChangeListener(changeListener);
        blueSpinner.addChangeListener(changeListener);

        previewPanel = new JPanel();
        previewPanel.setBackground(Color.BLACK);

        setLayout(new GridLayout(4, 2));

        add(redLabel);
        add(redSpinner);

        add(greenLabel);
        add(greenSpinner);

        add(blueLabel);
        add(blueSpinner);

        add(previewLabel);
        add(previewPanel);

        setAlwaysOnTop(true);
        setWindowOpacity(this, 0.85F);
        pack();
    }

    private class ColorSpinnerChangeListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            int r = (Integer) redSpinner.getValue();
            int g = (Integer) greenSpinner.getValue();
            int b = (Integer) blueSpinner.getValue();
            previewPanel.setBackground(new Color(r, g, b));
        }
    }

    private class PixelGrabberThread extends Thread implements Runnable {
        public PixelGrabberThread() {
            setPriority(Thread.MIN_PRIORITY);
        }
        @Override public void run() {
            while (true) {
                if (pixelGrabberToggle.isSelected()) {
                    PointerInfo pi = MouseInfo.getPointerInfo();
                    Point p = pi.getLocation();
                    int x = (int) p.getX();
                    int y = (int) p.getY();
                    Color c = robot.getPixelColor(x, y);
                    redSpinner.setValue(c.getRed());
                    greenSpinner.setValue(c.getGreen());
                    blueSpinner.setValue(c.getBlue());
                    previewPanel.setBackground(c);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        new PixelGrabber().setVisible(true);
    }

    private JMenuBar menuBar;
    private JMenu pixelGrabberMenu;
    private JCheckBoxMenuItem pixelGrabberToggle;
    private JCheckBoxMenuItem opacityToggle;
    private JLabel redLabel;
    private JSpinner redSpinner;
    private JLabel greenLabel;
    private JSpinner greenSpinner;
    private JLabel blueLabel;
    private JSpinner blueSpinner;
    private JLabel previewLabel;
    private JPanel previewPanel;
}
Attachments
PixelGrabber.zip
(4.73 KiB) Downloaded 113 times
Last edited by wearymemory on Fri Aug 20, 2010 12:58 pm, edited 1 time in total.
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Pixel Grabber in Java

Post by dandymcgee »

Definitely a handy tool to have. It was one of the first programs I ever made (in AutoIt there's a PixelGetColor(int screenX, int screenY) function ;) ). Gave RGB and Hex (HTML style) values.
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Re: Pixel Grabber in Java

Post by ajtgarber »

Neat! Do you really have to use reflection to set the window opacity though?
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: Pixel Grabber in Java

Post by Ginto8 »

This actually looks really cool! IDK what i'd use it for myself :lol: but it's definitely neat.
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
wearymemory
Chaos Rift Junior
Chaos Rift Junior
Posts: 209
Joined: Thu Feb 12, 2009 8:46 pm

Re: Pixel Grabber in Java

Post by wearymemory »

ajtgarber wrote:Neat! Do you really have to use reflection to set the window opacity though?
Not at all, but it's the preferred approach when using sun's packages because you can't rely on them being there between Java platforms. Here's an article on creating translucent and shaped windows . The word is, that this will become a reliable part of JDK 7's features.

Thanks everyone!
Post Reply