NOTICE: This version of the NSF Unidata web site (archive.unidata.ucar.edu) is no longer being updated.
Current content can be found at unidata.ucar.edu.
To learn about what's going on, see About the Archive Site.
"From: Bill Hibbard " wrote: > > Hi Lars, > > > I have some code that saves a java.awt.Component to a jpeg > > file. Is this what you need? > > Yes, if you are willing to send me yor code that > would be a big help. I am tryng to understand why > our code does not work. > > Cheers, > Bill Here it is. Give me feedback if you want. /** * Saves a component to a jpeg file * * * @param c component to save as a picture * @param defaultName default file name for saving picture * @param parent a frame that the FileDialog can be modal to * @return true if successful * @author originally written by K.Kal, * but significant changes and this version by Lars Roe roex0029@xxxxxxxxxx, */ public static boolean saveJPEG(Component c, String defaultName, Frame parent) { boolean worked = false; //Use appropriate initializer for directory here, if needed String defaultDirectory = System.getProperty("user.home",""); String filename; FileDialog fd; Component frame = null; try { //Get filename fd = new FileDialog(parent, "Save in jpeg format", FileDialog.SAVE); fd.setDirectory(defaultDirectory); fd.setFile(defaultName); fd.setVisible(true); filename = fd.getFile(); filename = defaultDirectory + "/" + defaultName; //Save it to the file //For some reason, I can't get Swing components // (descendants of JComponent, not JFrame/JWindow/JDialog) // to get the graphics correctly, so I use a component which // is not to get the graphics (frame). Note: frame need not // be a Frame, but in many cases it is. frame = c; while (frame instanceof JComponent) { frame = frame.getParent(); } java.awt.Dimension area = c.getSize(); Point p1 = frame.getLocationOnScreen(); Point p2 = c.getLocationOnScreen(); java.io.FileOutputStream out = new java.io.FileOutputStream(filename); java.awt.image.BufferedImage bi = null; bi = (java.awt.image.BufferedImage) c.createImage(area.width, area.height); java.awt.Graphics g = bi.getGraphics(); g.translate((int) (p1.getX() - p2.getX()), (int) (p1.getY() - p2.getY())); frame.paintAll(g); com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(out); encoder.encode(bi); out.flush(); out.close(); //successful if this far worked = true; } catch (Exception e) { JOptionPane.showMessageDialog(DesktopWindow.defaultWindow, "Error Saving File", "Could Not Save File", JOptionPane.ERROR_MESSAGE); exception = e; } return worked; } -- Lars Roe 612-624-6711 roex0029@xxxxxxxxxx
visad
archives: