0

我有在屏幕上生成一对相关图表的代码,在单独的画布中。我希望将这两个图像保存到单独的文件中。但是当我使用相同的命令来保存它们时,一个正确保存,另一个保存为空白图像(仅背景颜色)。

画布之间有一个区别:一个被简单地绘制到,而另一个在屏幕外关联缓冲图像,因此我可以用鼠标拖动一条线穿过它。

设置此缓冲排列的代码是

public class VolCanvas extends Canvas
{

   volCnv.createBufferStrategy(2);
   offScreen = volCnv.getBufferStrategy();
   if (offScreen != null) ofsg = (Graphics2D) offScreen.getDrawGraphics();


  // carry out draw operations with ofsg
   .
   .
   .   

   ofsg.dispose();
   offscreen.show();
}

然后在保存到文件之前,我通过该函数将画布转换为图像

private BufferedImage canvasToImage(Canvas cnvs)
{
   int w = cnvs.getWidth();
   int h = cnvs.getHeight();
   int type = BufferedImage.TYPE_INT_RGB;
   BufferedImage image = new BufferedImage(w,h,type);
   Graphics2D g2 = image.createGraphics();
   cnvs.paint(g2);
   g2.dispose();
   return image;
 }//canvasToImage

最后,我在如下所示的 ActionListener 中进行了保存。

public class SaveChart implements ActionListener
{
   public void actionPerformed(ActionEvent evt)
   {
      File outFile;
      String outDirName = "", fileName;
      BufferedImage outImage;

      outImage = canvasToImage(graphCnv); 
      outDirName = Global.directory + "images/";
      outFile = new File(outDirName);
      fileDlgBox.setCurrentDirectory(outFile);    //setting the target directory
      fileDlgBox.showSaveDialog(null);
      outFile = fileDlgBox.getSelectedFile();
      try
      {
         ImageIO.write(outImage, "PNG", outFile);
      }
      catch(IOException ioe){}

      outImage = canvasToImage(volCnv);
      fileName = outFile.getName();
      fileName = outDirName + fileName + "_vol";
      outFile = new File(fileName);
     try
     {
        ImageIO.write(outImage, "PNG", outFile);
     }
     catch(IOException ioe){}
  }//actionPerformed
}//SaveChart

关于最后一个代码,第一次保存完美,它的相关画布只是一个画布。如前所述,第二个保存故障,即与屏幕外组件一起使用的画布。

对于这个问题的长度,我深表歉意,但人们通常希望查看所有相关代码,所以在这里。

提前感谢您对这个谜团的任何见解。

约翰·多纳

4

1 回答 1

5

试试这个代码

public void Crear_Imagen(Image image)
{
    try 
    {
        BufferedImage bi = (BufferedImage) image;
        File outputfile = new File("name.png");
        ImageIO.write(bi, "png", outputfile);
    } catch (IOException e) 
    {
    }
}
于 2011-08-06T04:52:15.410 回答