How to upload / save image from JPanel

I am missing the export file code, but I do not know what I need to add. I drew an image in the JPanel โ†’ panel and I want to save this image on my desktop. What do I need to add?

JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(panel); 

I added the following code to the paintComponent method:

 bi = new BufferedImage(panel.getSize().width,panel.getSize().height, BufferedImage.TYPE_INT_ARGB); g = bi.createGraphics(); 

And then the Save button does it ... What else am I missing? Or do it wrong.

 JFileChooser chooser = new JFileChooser(); chooser.showSaveDialog(panel); try{ImageIO.write(bi,"png",new File("test.png"));}catch (Exception ex) {} 
+4
source share
1 answer

You doubt that important information is missing: how do you draw things on JPanel? In my opinion, a smart way would be to insert into a BufferedImage and then just save the BufferedImage to a file using ImageIO.write(...)

Edit
You indicate:

I just draw polygons on a class that extends JPanel. I create them using the paintComponent method.

Again, I recommend that you draw them in a BufferedImage, getting the Graphics context, drawing an image using this Graphics object, and then deleting the Graphics object. You can display the BufferedImage in the JPanel method of paintComponent(...) by calling g.drawImage(...) . Then, if you want to save the drawing, again just save the BufferedImage.

+6
source

Source: https://habr.com/ru/post/1441433/


All Articles