我想获取BufferedImage上像素的颜色。我将BufferedImage的背景设置为白色,然后在BufferedImage上绘制一条从(100,100)到(100,200)的线。然后,我将BufferedImage绘制到JPanel上。有线但背景不是白色。为什么呢?
此外,getRGB方法为R,G和B返回0,即使它不是getRGB(100,100)。有什么问题?
代码:
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);
}
}
答案 0 :(得分:4)
在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