Question

I am working to create a GUI that will save an Image drawn on a JLabel by a user. Here is the code that I have for my saveImage method. I can get the box to pop up so that I can select where to save the file, but no file is actually saved.

public void saveImage()
    {
        BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D image2 = image.createGraphics();
        image2.setBackground(Color.WHITE);
        image2.clearRect(0, 0, this.getWidth(), this.getHeight());
        this.paintAll(image2);
        try
        {
            File output = new File("rectangle.png");
            ImageIO.write(image, "Rectangles", output);
            final JFileChooser fchooser = new JFileChooser(".");
            int retvalue = fchooser.showSaveDialog(RectangleLabel.this);
            if (retvalue == JFileChooser.APPROVE_OPTION)
            {
                fchooser.setSelectedFile(output);
                File f = fchooser.getSelectedFile();
            }
        }
        catch(IOException ie)
        {

        }


    }

No correct solution

OTHER TIPS

First, you need to create an image of the component...

 BufferedImage img = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
 Graphics2D g2d = img.createGraphics();
 label.printAll(g2d);
 g2d.dispose();

Then you need to save it...

 ImageIO.write(img, "png", f);

Take a look at Writing/Saving an Image for more details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top