John R Doner
John R Doner

Reputation: 2282

Java save image to file problem

I have code that generates a pair of related graphs on the screen, in separate canvases. I wish to save both of these images to separate files. But when I use identical commands to save them, one saves correctly, the other as a blank image (background color only).

There is one distinction between the canvasses: one is simply drawn to, while the other has on off-screen associated buffered image, so that I can drag a line across it with the mouse.

The code for setting up this buffered arrangement is

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();
}

Then before saving to file, I do a canvas to image conversion via the function

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

Finally, I do a save in an ActiionListener shown below.

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

Regarding this last code, the first save works perfectly, and the relevant canvas for it was just a canvas. The second save malfunctions as earlier described, and that is the canvas used with an offscreen component.

I apologize for the length of this question, but people usually want to see all relevant code, so here it is.

Thanks in advance for any insights into this mystery.

John Doner

Upvotes: 0

Views: 8357

Answers (1)

cmujica
cmujica

Reputation: 1334

try this code

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) 
    {
    }
}

Upvotes: 6

Related Questions