1 package prefuse.util.display; 2 3 import java.awt.event.ActionEvent ; 4 import java.io.BufferedOutputStream ; 5 import java.io.File ; 6 import java.io.FileOutputStream ; 7 import java.io.OutputStream ; 8 import java.util.HashSet ; 9 10 import javax.imageio.ImageIO ; 11 import javax.swing.AbstractAction ; 12 import javax.swing.JFileChooser ; 13 import javax.swing.JOptionPane ; 14 15 import prefuse.Display; 16 import prefuse.util.io.IOLib; 17 import prefuse.util.io.SimpleFileFilter; 18 19 20 26 public class ExportDisplayAction extends AbstractAction { 27 28 private Display display; 29 private JFileChooser chooser; 30 private ScaleSelector scaler; 31 32 36 public ExportDisplayAction(Display display) { 37 this.display = display; 38 } 39 40 private void init() { 41 scaler = new ScaleSelector(); 42 chooser = new JFileChooser (); 43 chooser.setDialogType(JFileChooser.SAVE_DIALOG); 44 chooser.setDialogTitle("Export Prefuse Display..."); 45 chooser.setAcceptAllFileFilterUsed(false); 46 47 HashSet seen = new HashSet (); 48 String [] fmts = ImageIO.getWriterFormatNames(); 49 for ( int i=0; i<fmts.length; i++ ) { 50 String s = fmts[i].toLowerCase(); 51 if ( s.length() == 3 && !seen.contains(s) ) { 52 seen.add(s); 53 chooser.setFileFilter(new SimpleFileFilter(s, 54 s.toUpperCase()+" Image (*."+s+")")); 55 } 56 } 57 seen.clear(); seen = null; 58 chooser.setAccessory(scaler); 59 } 60 61 65 public void actionPerformed(ActionEvent evt) { 66 if ( chooser == null ) 68 init(); 69 70 File f = null; 72 scaler.setImage(display.getOffscreenBuffer()); 73 int returnVal = chooser.showSaveDialog(display); 74 if (returnVal == JFileChooser.APPROVE_OPTION) { 75 f = chooser.getSelectedFile(); 76 } else { 77 return; 78 } 79 String format = 80 ((SimpleFileFilter)chooser.getFileFilter()).getExtension(); 81 String ext = IOLib.getExtension(f); 82 if ( !format.equals(ext) ) { 83 f = new File (f.toString()+"."+format); 84 } 85 86 double scale = scaler.getScale(); 87 88 boolean success = false; 90 try { 91 OutputStream out = new BufferedOutputStream ( 92 new FileOutputStream (f)); 93 System.out.print("Saving image "+f.getName()+", "+ 94 format+" format..."); 95 success = display.saveImage(out, format, scale); 96 out.flush(); 97 out.close(); 98 System.out.println("\tDONE"); 99 } catch ( Exception e ) { 100 success = false; 101 } 102 if ( !success ) { 104 JOptionPane.showMessageDialog(display, 105 "Error Saving Image!", 106 "Image Save Error", 107 JOptionPane.ERROR_MESSAGE); 108 } 109 } 110 111 } | Popular Tags |