Reputation: 197
I want to get the colour of a pixel on a BufferedImage. I set the background of the BufferedImage to white and I draw a line from (100, 100) to (100, 200) on the BufferedImage. Then, I draw the BufferedImage onto a JPanel. There is the line but the background is not white. Why?
Also, the getRGB method returns 0 for R, G and B, even if it is not getRGB(100, 100). What is wrong?
The code:
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);
}
}
Upvotes: 2
Views: 365
Reputation: 437
After gbi.setBackground(Color.white)
add gbi.clearRect(0,0,bi.getWidth(), bi.getHeight());
clearRect()
paints the background color onto the image. If you just set the a new background color it doesn't change the image.
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);
}
This prints
255 255 255
255 255 255
Upvotes: 4