我有以下语句将缓冲的 jPanel 图像写入 .png
文件。它确实写了背景颜色,但不写图形。
BufferedImage image = new BufferedImage(jPanel.getWidth(),
jPanel.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
jPanel.paint(g);
ImageIO.write(image, "png", new File("testing.png"));
最佳答案
以这种方式使用 paint
会产生很多问题,除了调用双缓冲(这是不必要的开销)之外,当组件未在屏幕上实现时,它还会导致问题 -比如不绘制东西,甚至触发运行时异常。
作为一般经验法则,永远不要调用 paint
,而是使用 print
或 printAll
,例如。 .
BufferedImage image = new BufferedImage(jPanel.getWidth(), jPanel.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
jPanel.print(g);
g.dispose();
ImageIO.write(image, "png", new File("testing.png"));
另外,不要忘记,您应该对您创建的 Graphics
调用 dispose
,以确保它释放它可能创建的任何底层资源。
关于java - ImageIO只写入背景颜色,不写入图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745915/