我想获取 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);
}
}
最佳答案
在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
关于java - 获取 BufferedImage 上像素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248858/