【问题标题】:Get colour of pixel on a BufferedImage获取 BufferedImage 上像素的颜色
【发布时间】:2016-03-27 15:05:43
【问题描述】:

我想获取 BufferedImage 上像素的颜色。我将 BufferedImage 的背景设置为白色,然后在 BufferedImage 上画一条从 (100, 100) 到 (100, 200) 的线。然后,我将 BufferedImage 绘制到 JPanel 上。有线条但背景不是白色。为什么?

此外,对于 R、G 和 B,getRGB 方法返回 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);
    }
}

【问题讨论】:

标签: java swing colors pixel bufferedimage


【解决方案1】:

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

【讨论】:

  • 问题是因为背景没有出现?这也有效:gbi.setColor(Color.white) 后跟 gbi.fillRect(0, 0, 500, 500) 而不是 gbi.setBackground(Color.white) 后跟 gbi.clearRect(0, 0, 500, 500)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
相关资源
最近更新 更多