[英]Get colour of pixel on a BufferedImage
我想在BufferedImage上获得像素的颜色。 我将BufferedImage的背景设置为白色,并在BufferedImage上从(100,100)到(100,200)画了一条线。 然后,将BufferedImage绘制到JPanel上。 有线,但背景不是白色。 为什么?
另外,即使不是getRGB(100,100),getRGB方法也会为R,G和B返回0。 怎么了?
编码:
public class PixelColour extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
BufferedImage bi = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = bi.createGraphics();
gbi.setColor(Color.black);
gbi.setBackground(Color.white);
gbi.drawLine(100, 100, 100, 200);
g2.drawImage(bi, null, 0, 0);
int rgb = bi.getRGB(100, 100);
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = (rgb & 0xFF);
System.out.println(red + " " + green + " " + blue);
}
public static void main(String[] args) throws IOException{
PixelColour pc = new PixelColour();
JFrame frame = new JFrame("Pixel colour");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(pc);
frame.setSize(500,500);
frame.setVisible(true);
}
}
在gbi.setBackground(Color.white)
添加gbi.clearRect(0,0,bi.getWidth(), bi.getHeight());
clearRect()
将背景色绘制到图像上。 如果仅设置新的背景色,则不会更改图像。
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
BufferedImage bi = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = bi.createGraphics();
gbi.setColor(Color.black);
gbi.setBackground(Color.white);
// here
gbi.clearRect(0, 0, bi.getWidth(), bi.getHeight());
gbi.drawLine(100, 100, 100, 200);
g2.drawImage(bi, null, 0, 0);
int rgb = bi.getRGB(50, 50); // off the black line
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = (rgb & 0xFF);
System.out.println(red + " " + green + " " + blue);
}
此打印
255 255 255
255 255 255
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.