001 package nl.cwi.sen1.visplugin.screenshotmaker; 002 003 import java.awt.Dimension; 004 import java.awt.Graphics2D; 005 import java.awt.Rectangle; 006 import java.awt.image.BufferedImage; 007 import java.io.File; 008 import java.io.IOException; 009 010 import javax.imageio.ImageIO; 011 import javax.swing.JPanel; 012 013 /** 014 * ScreenshotMaker has the functionality to export a JPanel as an image 015 * 016 * @author R. Bergen 017 * @author S. Tharmarajah 018 * @date 09-03-2007 019 */ 020 public class ScreenshotMaker { 021 022 public static final String JPEG_EXTENSION = "jpg"; 023 public static final String PNG_EXTENSION = "png"; 024 public static final String DEFAULT_EXTENSION = PNG_EXTENSION; 025 026 /** 027 * Save a JPanel as an image to a given destination. 028 * 029 * @param JPanel The Jpanel which should be saved 030 * @param exportDestination The destination of the exported image 031 * @param fileExtension The extension of the exported image 032 * 033 * @author R. Bergen 034 * @author S. Tharmarajah 035 * @date 09-03-2007 036 */ 037 public static void saveScreenshot(JPanel jPanel, String exportDestination, String fileExtension) { 038 039 // check extensions 040 if (!fileExtension.equals(JPEG_EXTENSION) && !fileExtension.equals(PNG_EXTENSION)) { 041 fileExtension = DEFAULT_EXTENSION; 042 } 043 044 // make screenshot 045 BufferedImage bufferedImage = createImageFromPanel(jPanel); 046 047 // Check if file already exists, if so delete the existing file 048 File file = new File(exportDestination + "." +fileExtension); 049 boolean exists = file.exists(); 050 051 if(exists) 052 file.delete(); 053 054 // save to disk 055 try { 056 ImageIO.write(bufferedImage, fileExtension, file); 057 } catch (IOException e) { 058 // TODO: Throw the exception to a dialog in the Meta Studio 059 } 060 061 } 062 063 /** 064 * Create a BufferedImage from a given JPanel. 065 * 066 * @param JPanel The Jpanel which should be saved 067 * @return bufferedImage a BufferedImage of the given JPanel 068 * 069 * @author R. Bergen 070 * @author S. Tharmarajah 071 * @date 09-03-2007 072 */ 073 private static BufferedImage createImageFromPanel(JPanel jPanel) { 074 Dimension dimension = jPanel.getSize(); 075 Rectangle region = new Rectangle(0, 0, dimension.width, dimension.height); 076 077 BufferedImage bufferedImage = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB); 078 Graphics2D graphics2D = bufferedImage.createGraphics(); 079 jPanel.paint(graphics2D); 080 graphics2D.dispose(); 081 082 return bufferedImage; 083 } 084 085 086 }