Gezeichnetes als bild speichern

fd1234

Mitglied
Hallo, ich würde gerne mit graphics2d rechtecke zeichnen und dann als bild abspeichern, ich habe schon folgenden Ansatz:

Java:
public class KreisZeichnen extends JFrame {

    JPanel panel=new JPanel();

    public KreisZeichnen() {
        add(panel);

        this.setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
       
       
        BufferedImage bild = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bild.createGraphics();
        g.setColor( Color.black );
        g.fillRect( 1, 1, 200, 200 );
         g.setBackground(Color.black);
        panel.paint(g);
        try {
            ImageIO.write(bild, "jpeg", new File("Test1.jpeg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new KreisZeichnen();
    }

   
}

da kommt aber leider nur ein leeres Jpanel raus, was mache ich falsch
 
Also bei JavaFX wäre das extrem einfach: Alles was von Node ableitet - also auch das JavaFX-Canvas - hat eine SnapShot-Methode:
https://docs.oracle.com/javase/8/ja...tParameters-javafx.scene.image.WritableImage-
Was man damit machen kann, zeigt diese Antwort auf StackOverflow:
http://stackoverflow.com/a/22801589/1281217
You can convert your scene to an image using

Java:
WritableImage snapshot = scene.snapshot(null);

This will return a WritableImage, which can be converted to an Image File or BufferedImage, and print using the Printing API of JavaFX8 (there are not lot of examples available for this, but the new API has quite a resemblance to the old Printing API, so it won't be a problem)

Converting WritableImage to Png File

Java:
WritableImage snapshot = scene.snapshot(null);
File file =newFile("image.png");
try{
    ImageIO.write(SwingFXUtils.fromFXImage(snapshot,null),"png", file);
}catch(IOException e){
    e.printStackTrace();
}

Converting WritableImage to BufferedImage (used for printing)

Java:
WritableImage snapshot = scene.snapshot(null);
BufferedImage bufferedImage =SwingFXUtils.fromFXImage(snapshot,null);

For just a small example of how to print an Image using java, please go through

Proper way of printing a BufferedImage in Java

How to print image in java
 
Du zeichnest das JPanel auf dem Graphics2D des Images. Was du aber eigentlich tun möchtest, ist, das Image in der paintComponent des JPanels zu zeichnen.
Google mal nach "draw image on JPanel".
Warum kein JFreeChart?
 

Zurück
Oben