0

I have an image, I read the image, add a few things to image (like some text etc).

All this I do inside a JPanel.

Now, I want to save the resulting image to a .png file.

I think, there is a way to do this for a buffered image using ImageIO.write()

But I cannot convert the dynamically created image to a BufferedImage.

Is there a way I can go about this ?

akash
  • 22,664
  • 11
  • 59
  • 87
user966123
  • 631
  • 1
  • 9
  • 18
  • For [example](http://stackoverflow.com/questions/17690275/exporting-a-jpanel-to-an-image/17690351#17690351) – MadProgrammer Mar 20 '14 at 01:53
  • I tried using: BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); But all the values for the transparency parameter kept on giving an exception saying "Unknown Image type". – user966123 Mar 20 '14 at 02:01
  • You'd need to provide a runnable example before I would even be able to guess why. The example I linked works just fine... – MadProgrammer Mar 20 '14 at 02:07
  • Convert your image into BufferedImage. http://stackoverflow.com/questions/13605248/java-converting-image-to-bufferedimage – huocp Mar 20 '14 at 02:12

3 Answers3

2

You can use the Screen Image class.

It will create a BufferedImage of your JPanel. The class also has code to write the image to a file.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

All this I do inside a JPanel.

Do it instead in another BufferedImage displayed in a JLabel. The code can get a Graphics2D object using BufferedImage.createGraphics() method. Paint the image and text to the new Graphics2D instance and you then the new image can be saved directly, along with changes.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

Use Following method it worked for me...

void TakeSnapShot(JPanel panel,String Locatefile){  
           BufferedImage bi = new BufferedImage(panel.getSize().width,  panel.getSize().height,BufferedImage.TYPE_INT_RGB);  

           panel.paint(bi.createGraphics()); 

           File image = new File(Locatefile);  
        try{  
            image.createNewFile();  
            ImageIO.write(bi, "png", image);
        }catch(Exception ex){  
        }  
    }
akash
  • 22,664
  • 11
  • 59
  • 87