0

Can somebody please give me some advice about how to save an image (PNG) from my created graph?

This is the java program:

public class GraphingData extends JPanel {
    int[] data = {
             110, 535, 0, 459, 380, 199, 212, 722, 332, 836, 149, 10, 656, 465, 100, 173, 277, 381, 685, 988, 89, 585, 381, 779, 378, 769, 265, 10 
    };
    final int PAD = 20;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();

        .......
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new GraphingData());
        f.setSize(1000,500);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
ezzitt
  • 117
  • 2
  • 5
  • Possible dup to http://stackoverflow.com/questions/8202253/saving-a-java-2d-graphics-image-as-png-file? – vjkumar Apr 18 '16 at 09:19

1 Answers1

0

To store a panel how it currently shown on screen (sizes etc.) to a file just do

BufferedImage bi = new BufferedImage(panel.getSize().width, panel.getSize().height, BufferedImage.TYPE_INT_RGB);
panel.paint(bi.createGraphics());
ImageIO.write(bi, "PNG", new File("path/to/file.png"));

Besides that, do not use the Graphics that is given as parameter to paintComponent directly but call g.create() on it and if you are finished with that new instance call dispose() on it. You are expected to not change the Graphics object that is put in regarding colors, transformations and so on and with the create() and dispose() you make sure this is the case.

Vampire
  • 35,631
  • 4
  • 76
  • 102
  • Fantastic, work fine! Thank you My question now is how to make a change and to save my Image without f.setvisible (true) if I do f.setvisible (false) my saved Image is only in black – ezzitt Apr 18 '16 at 09:58