09-03
04

图片某点颜色抓取

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Robot;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Test extends JFrame {
    private static final long serialVersionUID = 1L;

    JScrollPane scrollPane;

    ImageIcon icon;

    Image image;

    Robot rb = null;

    public Test() {
    // ken.jpg要位于此java文件项目目录下,我的ide :eclipse
    icon = new ImageIcon("f:/1.jpg");

    JPanel panel = new JPanel() {

        private static final long serialVersionUID = 1L;

        protected void paintComponent(Graphics g) {
        g.drawImage(icon.getImage(), 0, 0, null);
        super.paintComponent(g);
        }
    };
    panel.setOpaque(false);
    panel.setPreferredSize(new Dimension(800, 600));
    panel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        // 转化成#ffffff格式
        Color c = rb.getPixelColor(x, y);
        String r = Integer.toHexString(c.getRed());
        String g = Integer.toHexString(c.getGreen());
        String b = Integer.toHexString(c.getBlue());
        if (r.length() == 1)
            r += "0";
        if (g.length() == 1)
            g += "0";
        if (b.length() == 1)
            b += "0";
        // color就是获得点颜色的字符串表示
        String color = "#" + r + g + b;
        System.out.println(color);
        }

    });
    scrollPane = new JScrollPane(panel);
    getContentPane().add(scrollPane);
    init();
    }

    public void init() {
    try {
        rb = new Robot();
    } catch (AWTException e) {
        e.printStackTrace();
    }
    }

    public static void main(String[] args) {
    Test frame = new Test();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }


[本日志由 blurxx 于 2009-03-04 03:32 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: 图片 抓取 GUI
相关日志:
评论: 0 | 引用: 0 | 查看次数: 460
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭