import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class GetRectPixel {
public GetRectPixel() {
ImageHolder holder = new ImageHolder();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(holder);
frame.getContentPane().add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
public static void main(String[] args) {
GetPixel getpixel = new GetPixel();
}
}
class ImageHolder extends Canvas{
BufferedImage bi ;//创建缓冲区图像
Image image;
MediaTracker mt ;//创建媒体跟踪器
int imageWidth; //图像宽度
int imageHeight;//图像高度
public ImageHolder() {
mt =new MediaTracker(this);
try{
image = Toolkit.getDefaultToolkit().createImage("gigi3.jpg");
mt.addImage(image,0);
mt.waitForAll();//等待直到所有的图像都以完成装填
imageWidth = image.getWidth(this);//获得单前图像的宽度
imageHeight = image.getHeight(this);//获得当前图像的长度
}
catch(Exception e){}
bi = new BufferedImage(imageWidth,imageHeight,BufferedImage.TYPE_INT_RGB);
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me){
//获得鼠标当前位置的横,纵坐标
int mouseX = (int)me.getPoint().getX();
int mouseY =(int) me.getPoint().getY();
//获得该处的rgb值
getPixel(mouseX,mouseY);
}
});
setSize(imageWidth,imageHeight);
}
public void paint(Graphics g){
int xCenter = (getSize().width / 2) - (imageWidth / 2);
int yCenter = (getSize().height / 2) - (imageHeight / 2);
g.drawImage(image, xCenter, yCenter, imageWidth, imageHeight, this);
}
public void getPixel(int x,int y){
//获得ImageHolder的色彩模型
ColorModel cm = this.getColorModel();
//把象素形式的色彩组件(ImageHolder)以rgb的形式返回。
int rgb = cm.getRGB(x*y);
//分别获得其r,g,b值。
int red = (rgb>>16)&0xff ;
int green = (rgb>>8)&0xff ;
int blue = (rgb)&0xff ;
System.out.println( "("+red+","+green+ ","+blue+ ")");
}
}