How can I take snapshots of Java components and save them into image files?

Bill Day

Java 2D's BufferedImages and Sun's JPEG encoder package make short work of this. In order to save snapshots from java.awt.Components into JPEG files, you simply:

  • Create a BufferedImage with the same dimensions as those of your Component.
  • Draw the contents of the Component into the BufferedImage.
  • Save the BufferedImage out to a file using the JPEG package and standard FileOutputStream.
Here's a quick example method that you can add to any of your Java 2/JDK 1.2 applications. Simply pass in the component you want to snapshot and the filename you want to save into.

     public void saveComponentAsJPEG(Component myComponent, String filename) {
       Dimension size = myComponent.getSize();
       BufferedImage myImage = 
         new BufferedImage(size.width, size.height,
         BufferedImage.TYPE_INT_RGB);
       Graphics2D g2 = myImage.createGraphics();
       myComponent.paint(g2);
       try {
         OutputStream out = new FileOutputStream(filename);
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
         encoder.encode(myImage);
         out.close();
       } catch (Exception e) {
         System.out.println(e); 
       }
     }  

This method is very versatile. It can be used to take snapshots of a wide variety of Java application components. Please do be forewarned, however, that you use com.sun.image.codec.jpeg at some risk to the portability of your code.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact