How to save transperant gif

I am building a generic graph package and I wanted to capture the graph (image) and save it into a GIF file with a transperent background.
I have been struggling with the transperant part for a whole day, but now I finally found how to do it and I just wanted to share this knowledge with the rest of you.
<b>1.) Generate the Graph</b>
I created two new methods BufferedImage getImage() and void drawImage( Graphics2D )
<pre>
public BufferedImage getImage( int width, int height ) {
BufferedImage bufImage = new BufferedImage( width, height, BufferedImage.TYPE_4BYTE_ABGR ); //Create a new BufferedImage
Graphics2D graphics2D = bufImage.createGraphics(); //Creates a Graphics2D, which can be used to draw into this BufferedImage
graphics2D.setColor( new Color( 255, 255, 255, 0 ) ); // The last int is the alpha value and 0 will make the Color transperent
graphics2D.fillRect( 0, 0, width, height ); // Fill a Rectangle with the same size as the image with the transparent color
drawImage( graphics2D ); //Draw the actual graph on the transparent Rectangle
return bufImage; //Return the BufferedImage
</pre>
<pre>
public void drawImage( Graphics2D g ) {
drawGraph( g ); //Draws the axis
putValues( g ); //Draws the actual values/graph
</pre>
<b>2.) Paint the Graph in you Component (Panel/JPanel, Frame/JFrame, etc)</b>
<pre>
public void paint( Graphics g ) {
Dimension bounds = this.getSize(); //Get the Dimension/Size of the Component
g.drawImage( getBufImage( bounds.width, bounds.height ), 0, 0, this ); //Get the BufferedImage and draw it on the Components Graphics Object
</pre>
<b>3.) Save the Graph into a GIF file</b>
<b>3.1. Download the Acme package to be able to save to GIF</b> (You will only need the GifEncoder, ImageEncoder and IntHashtable).
<b>3.2. Save to GIF</b>
<pre>
import Acme.*;
import Acme.JPM.Encoders.*;
public void saveGIF( String filename, int width, int height ) {
BufferedImage bufImage = getBufImage(); //Get the BufferedImage with the Graph drawn on a transparent Rectangle
Graphics2D graphics2D = bufImage.createGraphics();Creates a Graphics2D, which can be used to draw into this BufferedImage
graphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); //Sets the value of a single preference for the rendering algorithms
try {
GifEncoder gifcoder = new GifEncoder(bufImage, new BufferedOutputStream( new FileOutputStream( fileName + ".gif" ) ) ); //Create a new GIFEncoder for the BufferedImage and a OutputStream
gifcoder.encode(); //Write the image into GIF
catch( FileNotFoundException fnfe ) {
System.err.println( "error: MGraph.saveImage( String ): " + fnfe );
catch( IOException ioe ) {
System.err.println( "error: MGraph.saveImage( String ): " + ioe );
</pre>
That's it! I hope this will be helpful and save you some time.
/Max

I am also going to start to build some form of graphic plot toolkit for a project in my university. I would be great to know how you have defined your API and how the output of the graphs look like. If you are willing to share that?
Regards,
Peter.

Similar Messages

  • How to save in GIF or JPEG format?

    I make a drawing using Graphics objects and now i want to save it to a GIF or JPEG or BMP file.
    How to go about it?
    TIA
    Naveen

    Hi,
    Here is some code that may help.
    NOTES: pixels were recieved from a PixelGrabber proccess.
    transColor was picked from an image (you can supply your own code its just an int).
    blnTrans is a boolean flag indicating that a transparaent color was picked.
    dim is the dimensions of the image (any image will do).
    import javax.swing.*;
    import javax.media.jai.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import com.sun.image.codec.jpeg.*;
    import com.sun.media.jai.codec.ImageCodec;
    import com.sun.media.jai.codec.ImageEncoder;
    import com.sun.media.jai.codec.PNGEncodeParam;
    import com.sun.media.jai.codec.BMPEncodeParam;
    import com.sun.media.jai.codec.TIFFEncodeParam;
    import java.awt.image.*;
    import java.awt.color.*;
    import Acme.JPM.Encoders.*;
    //Some more Code
    int fileType = 0;
    File file = null;
    if (pixels != null)
    //create a file save dialog.
    //create a File Chooser.
    fc = new JFileChooser(););
    int returnValue = fc.showSaveDialog(this);
    //detemine the choose.
    if (returnValue == JFileChooser.APPROVE_OPTION)
    file = fc.getSelectedFile();
    //get the file ext and translate for switch.
    Utils ut = new Utils();
    String ext = ut.getExtension(file);
    if (ext.equals("gif"))
    fileType = 0;
    else if (ext.equals("jpg"))
    fileType = 1;
    else if (ext.equals("png"))
    fileType = 2;
    else if (ext.equals("tif"))
    fileType = 3;
    else if (ext.equals("bmp"))
    fileType = 4;
    switch (fileType)
    case 0:
    if (blnTrans)
    NewImageProducer img = new NewImageProducer(pixels, TransColor, dim);
    try
    FileOutputStream fos1 = new FileOutputStream(file);
    Acme.JPM.Encoders.ImageEncoder e = new GifEncoder(img, fos1);
    e.encode();
    fos1.close();
    catch (java.io.IOException e) {}
    else
    BufferedImage imb = new BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_RGB);
    imb.setRGB(0, 0, (int)dim.getWidth(), (int)dim.getHeight(), pixels, 0, (int)dim.getWidth());
    try
    FileOutputStream fos2 = new FileOutputStream(file);
    Acme.JPM.Encoders.ImageEncoder e = new GifEncoder(imb, fos2);
    e.encode();
    fos2.close();
    catch (java.io.IOException e) {}
    catch (Exception er) {}
    break;
    case 1:
    try
    BufferedImage bimg = new java.awt.image.BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_RGB);
    bimg.setRGB(0, 0, (int)dim.getWidth(), (int)dim.getHeight(), pixels, 0, (int)dim.getWidth());
    //Encode as a JPEG
    FileOutputStream fos3 = new FileOutputStream(file);
    JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos3);
    jpeg.encode(bimg);
    fos3.close();
    catch (java.io.IOException e) {}
    break;
    case 2:
    try
    BufferedImage bimg = new java.awt.image.BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_RGB);
    bimg.setRGB(0, 0, (int)dim.getWidth(), (int)dim.getHeight(), pixels, 0, (int)dim.getWidth());
    //Encode as a PNG
    FileOutputStream fos3 = new FileOutputStream(file);
    PNGEncodeParam pp = PNGEncodeParam.getDefaultEncodeParam(bimg);
    ImageEncoder png = ImageCodec.createImageEncoder("PNG", fos3, pp);
    png.encode(bimg);
    fos3.close();
    catch (java.io.IOException e) {}
    break;
    case 3:
    try
    BufferedImage bimg = new java.awt.image.BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
    bimg.setRGB(0, 0, (int)dim.getWidth(), (int)dim.getHeight(), pixels, 0, (int)dim.getWidth());
    //Encode as a TIF
    FileOutputStream fos3 = new FileOutputStream(file);
    TIFFEncodeParam tp = new TIFFEncodeParam();
    ImageEncoder tif = ImageCodec.createImageEncoder("TIFF", fos3, tp);
    tif.encode(bimg);
    fos3.close();
    catch (java.io.IOException e) {}
    break;
    case 4:
    try
    BufferedImage bimg = new java.awt.image.BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    bimg.setRGB(0, 0, (int)dim.getWidth(), (int)dim.getHeight(), pixels, 0, (int)dim.getWidth());
    //Encode as a BMP
    FileOutputStream fos3 = new FileOutputStream(file);
    BMPEncodeParam bp = new BMPEncodeParam();
    ImageEncoder png = ImageCodec.createImageEncoder("BMP", fos3, bp);
    png.encode(bimg);
    fos3.close();
    catch (java.io.IOException e) {}
    break;
    } //end of switch.
    } //end of file option.
    //Here is NewImageProducer
    import java.awt.image.*;
    import java.util.*;
    import java.awt.*;
    import java.applet.*;
    import java.awt.color.*;
    class NewImageProducer implements ImageProducer{
    private Vector vector = null;
    int[] pixels;
    int alpha;
    Dimension dim;
    public NewImageProducer(int[] pixels, int alpha, Dimension dim){
    vector = new Vector();
    this.pixels = pixels;
    this.alpha = alpha;
    this.dim = dim;
    public void addConsumer(ImageConsumer ic){
    if (isConsumer(ic) == false)
    vector.addElement(ic);
    public void removeConsumer(ImageConsumer ic){
    if (isConsumer(ic) == true)
    vector.removeElement(ic);
    public boolean isConsumer(ImageConsumer ic){
    return vector.indexOf(ic) > -1;
    public void startProduction(ImageConsumer ic){
    addConsumer(ic);
    int x = (int)dim.getWidth();
    int y = (int)dim.getHeight();
    Hashtable ht = new Hashtable();
    byte[] r = new byte[pixels.length];
    byte[] g = new byte[pixels.length];
    byte[] b = new byte[pixels.length];
    byte[] a = new byte[pixels.length];
    for (int i=0; i<pixels.length; i++)
    if (pixels[i] == alpha)
    a[i] = (byte)0;
    else
    a[i] = (byte)255;
    for (int i=0; i<pixels.length; i++)
    r[i] = (byte)((pixels[i] & 0xFF0000) >> 16);
    g[i] = (byte)((pixels[i] & 0x00FF00) >> 8);
    b[i] = (byte)(pixels[i] & 0x0000FF);
    ColorModel cm=null;
    try{
    cm = new IndexColorModel(8, pixels.length, r, g, b, a);
    catch (Exception e){e.printStackTrace();}
    Vector v = (Vector)vector.clone();
    Enumeration e = v.elements();
    while (e.hasMoreElements()){
    ic = (ImageConsumer)e.nextElement();
    ic.setColorModel(cm);
    ic.setDimensions(x, y);
    ic.setProperties(ht);
    ic.setHints(ImageConsumer.RANDOMPIXELORDER);
    int[] p = new int[pixels.length];
    for (int i=0; i<pixels.length; i++)
    p[i] = i;
    ic.setPixels(0, 0, x, y, cm, p, 0, x);
    ic.imageComplete(ImageConsumer.STATICIMAGEDONE);
    public void requestTopDownLeftRightResend(
    ImageConsumer ic){;
    //Here is Utils
    import java.io.File;
    public class Utils {
    public final static String jpeg = "jpeg";
    public final static String jpg = "jpg";
    public final static String gif = "gif";
    public final static String tiff = "tiff";
    public final static String tif = "tif";
    public final static String png = "png";
    public final static String bmp = "bmp";
    * Get the extension of a file.
    public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');
    if (i > 0 && i < s.length() - 1) {
    ext = s.substring(i+1).toLowerCase();
    return ext;
    Get the Acme class at:
    http://www.acme.com/java/software/Package-Acme.JPM.html

  • I'm using OSX 10.7.4 how do I convert gif files to jpeg? Preview does not have a "save as" choice.

    I'm using OSX 10.7.4 how do I convert gif files to jpeg? Preview does not have a "save as" choice.

    GraphicConverter (the best shareware ever devised for the Mac) will do this for you:
    http://www.lemkesoft.com/

  • How to save applet in image(gif/jpeg) format

    Hi there !
    how to save applet in image (gif/jpeg) format. i have just gone through JIMI package where serilization is there ,WHERE U CAN SORE in image format ...........can anybudy help me out.........if possible then pleeez provide me some example.
    Thanks in advan...........

    I think that is possible because i have seen some commercial applets that do that.
    -http://www.izhuk.com/painter/
    -http://www.lawrencegoetz.com/programs/signature/
    Thses two saves the image in the server since applets cant write in the host they are running. Maybe it would be possible whit JFS, i don't know.
    For now I am trying to store an image draw in the applet on my server.
    My idea now is copying the image to a buffer or something, open a connection to the server and receive the image with a perl CGI.
    There is an example with text:
    -http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html
    I want to do something similar but with an image.

  • How to save copyright information into Gif files?

    URGENT - can someone please help. i have photoshop cc and I need to know how to copyright my gif files

    c. is correct in that it's a little ambiguous what you're trying to achieve. Here are three ways:
    Under US law your image is already copyrighted at the moment you create it, but you greatly improve your legal standing in court if you register the image with the US Copyright Office.
    To add invisible copyright metadata inside an image, choose File > File Info in Photoshop, click the Description tab, and fill out Copyright Status and Copyright Notice. Then do what c. said in Save for Web to make sure it's included on export. However, while this works with most formats including JPG and PNG, I do not think it will work with a GIF. As far as I can tell, GIF doesn't support metadata. If you want better support for modern standards for non-photographic web graphics, use PNG instead of GIF.
    To add a visible copyright watermark over the image, download the Adobe Watermark panel and install it.

  • How to save simple graphics drawn on canvas as gifs, bitmaps, etc.

    I figured out how to draw a graphics object which is abstract for an application rather than an applet. Now, my question is, how do I save these simple graphics (lines, rectangles, circles,etc) drawn on canvas as gifs, bitmaps, etc. so that they may later be opened using other graphical viewers.
    another question I was wondering was if graphics is a AWT only class (ie no better swing equivalent)
    thanks

    some things i have found so far are acme or java advanced imaging api... anyone know what is easier to use for my purpose?
    it appears that when using acme, i need to use java.awt.image (does that mean I would have to convert the canvas to an image?) how do i save in gif format using java advanced imaging?
    Please help

  • Anyone know how to Save an Java Image to gif or png file?

    I'm trying to build a Map Edito for game, I want to import some images which and a lot of tiles in each of them. I want to cut each tile 24x24 out, then save it in an invidual file.
    Anyone know how to save to file? any easy way?
    I know there is somehthing call JPEGEncoding to save into jpeg...
    thanks!

    Java Advanced Imaging does it nicely, take a look.
    I do not remember the extact syntax right now, but have used it in the past.

  • How To save a music file from an email

    PLEASE HELP ME I CANT FIGURE OUT HOW TO SAVE SONG FROM MY ITUNES LIBRARY THAT U SENT TO MY EMAIL
    Post relates to: Pixi Plus p8wu0 (AT&T)

    Open email attachments
    You can receive any kind of file sent to you in email, but you can open an
    attachment only if your phone has an application that can open the file type.
    To open a single attachment: Tap the attachment name to download the
    attachment. If the attachment is a supported file type (MP3, PDF, DOC,
    XLS, PPT, GIF, or JPG), it opens automatically.
    To open multiple attachments: Tap the list of attachment names to view
    the attachments, and tap an attachment name to open the file.
    Save attachments;
    When you open attachments of certain file types, you can save them to your
    phone so you can view them later in one of your phone’s applications.
    1. Open the attachment (see Open email attachments).
    2. Do one of the following:
    • For pictures in JPG, GIF, BMP or PNG format, tap Copy To Photos.
    • For other file types, open the application menu and tap Save As. If
    the Save As menu item is not available, you cannot save the
    attachment.
    To open a saved attachment on your phone, open the application that can
    display the attachment. The attachment appears in the list of available files.
    Tap the file to open it.
    You can find this info. on page 74 of the user guide.
    For reference purposes, click on the following link for the support page for your device on the kb.palm.com webpage.
    http://kb.palm.com/wps/portal/kb/na/pixi/pixi/att/home/page_en.html
    There are links on the page to the user guide, troubleshooting, how to's, downloads, etc.

  • Save as gif file

    Hi all,
    I wanted to capture the mouse movements,and diplay it and save to gif file...
    what i did is ,i captured the X and Y co-ordinates...drawn it in a panel....now ..how can i save it to GIF file...
    please help me...
    thanks in advance...

    the only way i know is jai (java advanced imaging).
    link: http://java.sun.com/products/java-media/jai/index.html
    are there any people who know how to implement saving to gif in jai ?
    tobias

  • How to save HTML

    i need to know how to save an HTML file of a visited website being entered
    from a textField. I want it to be able to save the picture files as well..
    as an example when u key in http://www.yahoo.com i gets the HTML files and
    and the WHOLE image files contains in http://www.yahoo.com and save it to a certain directory. Just like when u visited a website and u click save as in IE, u can get the HTML files and all the image files from the website.
    thx..

    alright.. so this is the portion of my code.. i am suppose to download the image to a certain folder.. but so far it can only extract the HTML content to a textArea i provided. and the temp.indexOf("extension") does not work in my program.. but i works in my friends program.. pls tell me what went wrong.. and how to save the whole image files into a certain folder.
    try
    String strimg, temp;
         a=0;
         b=a+5;
                                       htmlArea.setText("");
                                       cmbimg.removeAllItems();
                                       connectionArea.append("* Processing request by "+s.getInetAddress().getHostAddress()+" to "+msg+" ......");
                                       URL url=new URL(msg); // value taken from client request
                                       BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
    // this is the portion that extract the HTML files
                                       do
                                            temp=in.readLine();
                                            if (temp.indexOf("jpg")>1 || temp.indexOf("gif")>1 || temp.indexOf("JPG")>1 || temp.indexOf("GIF")>1)
                                                 //Assigning 'a' a Value.
                                                 if( temp.indexOf("src")>1 || temp.indexOf("SRC")>1 )
                                                      if( temp.indexOf("src")>1)
                                                           a=temp.indexOf("src");
                                                      else
                                                           a=temp.indexOf("SRC");
                                                 //Assigning 'b' a Value.
                                                 if ( temp.indexOf("jpg")>1 )
                                                      b=temp.indexOf("jpg");
                                                 //Assigning 'b' a Value.
                                                 else if (temp.indexOf("gif")>1)
                                                      b=temp.indexOf("gif");
                                                 //Assigning 'b' a Value.
                                                 else if ( temp.indexOf("JPG")>1 )
                                                      b=temp.indexOf("JPG");
                                                 //Assigning 'b' a Value.
                                                 else if (temp.indexOf("GIF")>1)
                                                      b=temp.indexOf("GIF");
                                                 strimg=temp.substring(a+5,b+3);
                                                 cmbimg.addItem(strimg); //cmbing is a JCombobox
                                            //EXRTRACT IMAGES FROM SITE
                                            strimg=temp.substring(a+5,b+3);
                                            cmbimg.addItem(strimg);
                                            if (temp.equals(null))
                                                 temp="";
                                            htmlArea.setText(htmlArea.getText() + "\n" + temp); //htmlArea is the text area to display the extracted HTML content
                                       }while(!temp.equals(null));
                                  catch(java.net.ConnectException eNet){
                                       System.out.println("Connection Failed....");
                                  catch(NullPointerException e){
                                  catch(MalformedURLException eNet1){
                                       connectionArea.append("\n* "+msg+" is an Invalid Address");
                                       count = 1;
                                  catch(Exception e){
                                       connectionArea.append("\n* Unable to Connect to: "+msg+"\n");
                                       count = 1;
                                  }

  • How to save feathering in web and web/devices?

    I've scanned a page of handwriting, then used Photoshop CS4 to feather the border. But when I move the PSD to web and devices to compress and make the image a gif, I lose the feathered border> instead, I have a hard edge with rounded corners.
    Can someone please tell me how to save the feathered border when I save to web and devices?
    Thank you.

    Thank you, Marian. I wasn't aware that gifs don't allow transparencies. Just did some reading to understand it better.
    I tried to save the image in web/devices as a png, but the feathering wasn't holding up for that either. But I figured out a work-around. Not sure I could duplicate it, though.

  • How to save diagramm in HTML format or PDF it

    how to save diagramm in HTML format or PDF it

    You have two alternatives. First of all, there are many utilities, some of them free that can put a "printer" on your printer list that really writes a PDF file. The one I use is free, called CutePDF. Once you have one of these installed, saving to PDF is as simple as print the diagram, choose the printer associated with your utility, then name the file.
    I'm not sure if it is in your version of Designer, but all of the latest versions of Designer have a "publish diagram" utility. Just drop down the Utilities menu from the RON or the Design Editor. The bottom selection should be "Publish Diagrams...", which will open a dialog window. Choose the diagram(s) you want to publish, select Publish to File, enter a file name, and select a graphics format from PNG, GIF, JPEG, BMP or TIFF. You can easily add the file to an HTML page inside an &lt;IMG&gt; tag.

  • How  to  save  content of a  whole  swing  page

    Hi everyone ..
    can any of u tell me ,how to save contents of a java swing page in a single file with all components viz . textfield,textarea,JTable,JPanel etc .. with their respective formatting ie.e Font,Color etc ..
    Plz let me know it soon .. its very urgent ..
    Can I save it as Screenshot or Jpeg Image .. or how to go about it .
    Mohit

    Sure: see below!
    WARNING: this code will not compile as is because it uses some other classes from my personal code library (FileUtil & StringUtil). The particular methods of those classes which are used below are trivial methods that anyone can write, which is is why I have not posted them as well. So, to get the code below to compile, you can
    a) write your own versions of these classes or
    b) simply add the necessary methods to this class or
    c) simply comment out their usage (in the case of StringUtil, which is just used for arg checking)
    But if you still want me to post them, then I can post the relevant fragments of those classes.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import bb.io.FileUtil;
    import bb.util.StringUtil;
    * Class which supports taking screen shots of the entire desktop, AWT Components, or Swing JComponents.
    * This functionality is implemented in a series of <code>take</code> methods, each of which returns a BufferedImage.
    * This class also offers convenience <code>write</code> methods for storing BufferedImages to files.
    * <p>
    * The images taken by this class should be the precise images seen on the screen.
    * <b>However, the images written to files may deviate from the originals.</b>
    * One obvious cause is limitations of the chosen file format (especially with lossy formats like jpeg).
    * A subtle issue can occur, however, even when using lossless formats like png:
    * if the file is subsequently opened by another application,
    * that application may rescale the image, which can often cause visible artifacts.
    * <blockquote>
    *     To see this last problem on Windows XP,
    *     call {@link #take()} which returns an image of the entire desktop and write it to a file,
    *     and then open the file with XP's default graphics file viewer ("Windows Picture And Fax Viewer").
    *     This program shrinks the desktop image in order to fit it inside the program's window,
    *     and rescaling artifacts are readily seen, especially if the desktop image has any kind of text in it.
    *     If "Windows Picture And Fax Viewer" instead cropped the image or had a scroll pane, then this should not happen.
    * </blockquote>
    * <p>
    * Acknowledgement: this class was inspired by the program
    * <a href="http://www.discoverteenergy.com/files/ScreenImage.java">ScreenImage</a>.
    * Differences from the above program:
    * <ol>
    *  <li>this class uses {@link BufferedImage#TYPE_INT_ARGB} instead of {@link BufferedImage#TYPE_INT_RGB} in order to preserve alpha</li>
    *  <li>this class's {@link #formatNameDefault default image file format} is PNG instead of JPEG</li>
    *  <li>this class's <code>take</code> methods simply take snapshots and never have the side effect of writing image files</li>
    *  <li>this class added a version of <code>take</code> which can get a snapshot of a region of a Component</li>
    *  <li>
    *          when taking a snapshot of a region of a Component or JComponent,
    *          the Rectangle that specifies the region always has coordinates relative to the origin of the item
    *  </li>
    * </ol>
    * See also:
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=57&threadID=597936">forum discussion #1 on screen shots</a>
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=256&threadID=529933">forum discussion #2 on screen shots</a>
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=57&threadID=622393">forum discussion #3 on screen shots</a>.
    * <p>
    * It might appear that this class is multithread safe
    * because it is immutable (both its immediate state, as well as the deep state of its fields).
    * However, typical Java gui code is not multithread safe, in particular, once a component has been realized
    * it should only be accessed by the event dispatch thread
    * (see <a href="http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#1">Multithreading In Swing</a>
    * and <a href="http://java.sun.com/developer/JDCTechTips/2004/tt0611.html#1">More Multithreading In Swing</a>).
    * So, in order to enforce that requirement, all methods of this class which deal with components
    * require the calling thread to be the event dispatch thread.
    * See the javadocs of each method for its thread requirements.
    * <p>
    * @author bbatman
    public class ScreenShot {
         // -------------------- constants --------------------
         * Defines the image type for the BufferedImages that will create when taking snapshots.
         * The current value is {@link BufferedImage#TYPE_INT_ARGB}, which was chosen because
         * <ol>
         *  <li>the 'A' in its name means that it preserves any alpha in the image (cannot use the "non-A" types)</li>
         *  <li>the "_INT" types are the fastest types (the "BYTE" types are slower)
         * </ol>
         * @see <a href="http://forum.java.sun.com/thread.jspa?threadID=709109&tstart=0">this forum posting</a>
         private static final int imageType = BufferedImage.TYPE_INT_ARGB;
         * Default value for the graphics file format that will be written by this class.
         * The current value is "png" because the PNG format is by far the best lossless format currently available.
         * Furthermore, java cannot write to GIF anyways (only read).
         * <p>
         * @see <a href="http://www.w3.org/TR/PNG/">Portable Network Graphics (PNG) Specification (Second Edition)</a>
         * @see <a href="http://www.w3.org/QA/Tips/png-gif">GIF or PNG</a>
         * @see <a href="http://www.libpng.org/pub/png/">PNG Home Site</a>
         public static final String formatNameDefault = "png";
         // -------------------- take --------------------
         // desktop versions:
         * Takes a screen shot of the entire desktop.
         * <p>
         * Any thread may call this method.
         * <p>
         * @return a BufferedImage representing the entire screen
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take() throws AWTException, SecurityException {
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return take(region);
         * Takes a screen shot of the specified region of the desktop.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param region the Rectangle within the screen that will be captured
         * @return a BufferedImage representing the specified region within the screen
         * @throws IllegalArgumentException if region == null; region's width and height are not greater than zero
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Rectangle region) throws IllegalArgumentException, AWTException, SecurityException {
              if (region == null) throw new IllegalArgumentException("region == null");
              return new Robot().createScreenCapture( region );     // altho not currently mentioned in its javadocs, if you look at its source code, the Robot class is synchronized so it must be multithread safe, which is why any thread should be able to call this method
         // AWT Component versions:
         * Takes a screen shot of that part of the desktop whose area is where component lies.
         * Any other gui elements in this area, including ones which may lie on top of component,
         * will be included, since the result always reflects the current desktop view.
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param component AWT Component to take a screen shot of
         * @return a BufferedImage representing component
         * @throws IllegalArgumentException if component == null; component's width and height are not greater than zero
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Component component) throws IllegalArgumentException, IllegalStateException, AWTException, SecurityException {
              if (component == null) throw new IllegalArgumentException("component == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Rectangle region = component.getBounds();
              region.x = 0;     // CRITICAL: this and the next line are what make region relative to component
              region.y = 0;
              return take(component, region);
         * Takes a screen shot of that part of the desktop whose area is the region relative to where component lies.
         * Any other gui elements in this area, including ones which may lie on top of component,
         * will be included, since the result always reflects the current desktop view.
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param component AWT Component to take a screen shot of
         * @param region the Rectangle <i>relative to</i> component that will be captured
         * @return a BufferedImage representing component
         * @throws IllegalArgumentException if component == null; component's width and height are not greater than zero; region == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Component component, Rectangle region) throws IllegalArgumentException, IllegalStateException, AWTException, SecurityException {
              if (component == null) throw new IllegalArgumentException("component == null");
              if (region == null) throw new IllegalArgumentException("region == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Point p = new Point(0, 0);
              SwingUtilities.convertPointToScreen(p, component);
              region.x += p.x;
              region.y += p.y;
              return take(region);
         // Swing JComponent versions:
         * Takes a screen shot of <i>just</i> jcomponent
         * (no other gui elements will be present in the result).
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param jcomponent Swing JComponent to take a screen shot of
         * @return a BufferedImage representing jcomponent
         * @throws IllegalArgumentException if jcomponent == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         public static BufferedImage take(JComponent jcomponent) throws IllegalArgumentException, IllegalStateException {
              if (jcomponent == null) throw new IllegalArgumentException("jcomponent == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Dimension d = jcomponent.getSize();
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return take(jcomponent, region);
         * Takes a screen shot of <i>just</i> the specified region of jcomponent
         * (no other gui elements will be present in the result).
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param jcomponent Swing JComponent to take a screen shot of
         * @param region the Rectangle <i>relative to</i> jcomponent that will be captured
         * @return a BufferedImage representing the region within jcomponent
         * @throws IllegalArgumentException if jcomponent == null; region == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         public static BufferedImage take(JComponent jcomponent, Rectangle region) throws IllegalArgumentException, IllegalStateException {
              if (jcomponent == null) throw new IllegalArgumentException("jcomponent == null");
              if (region == null) throw new IllegalArgumentException("region == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              boolean opaquenessOriginal = jcomponent.isOpaque();
              Graphics2D g2d = null;
              try {
                   jcomponent.setOpaque( true );
                   BufferedImage image = new BufferedImage(region.width, region.height, imageType);
                   g2d = image.createGraphics();
                   g2d.translate(-region.x, -region.y) ;     // CRITICAL: this and the next line are what make region relative to component
                   g2d.setClip( region );
                   jcomponent.paint( g2d );
                   return image;
              finally {
                   jcomponent.setOpaque( opaquenessOriginal );
                   if (g2d != null) g2d.dispose();
         // -------------------- write --------------------
         * Writes image to a newly created File named fileName.
         * The graphics format will either be the extension found in fileName
         * or else {@link #formatNameDefault} if no extension exists.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param image the BufferedImage to be written
         * @param fileName name of the File that will write image to
         * @throws IllegalArgumentException if image == null; fileName is blank
         * @throws IOException if an I/O problem occurs
         public static void write(BufferedImage image, String fileName) throws IllegalArgumentException, IOException {
              if (image == null) throw new IllegalArgumentException("image == null");
              if (StringUtil.isBlank(fileName)) throw new IllegalArgumentException("fileName is blank");
              File file = new File(fileName);
              String formatName = FileUtil.getExtension(file);
              if (formatName.length() == 0) formatName = formatNameDefault;
              write(image, formatName, file);
         * Writes image to file in the format specified by formatName.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param image the BufferedImage to be written
         * @param formatName the graphics file format (e.g. "pnj", "jpeg", etc);
         * must be in the same set of values supported by the formatName arg of {@link ImageIO#write(RenderedImage, String, File)}
         * @param file the File that will write image to
         * @throws IllegalArgumentException if image == null; type is blank; file == null
         * @throws IOException if an I/O problem occurs
         public static void write(BufferedImage image, String formatName, File file) throws IllegalArgumentException, IOException {
              if (image == null) throw new IllegalArgumentException("image == null");
              if (StringUtil.isBlank(formatName)) throw new IllegalArgumentException("formatName is blank");
              if (file == null) throw new IllegalArgumentException("file == null");
              ImageIO.write(image, formatName, file);
         // -------------------- Test (inner class) --------------------
         * An inner class that consists solely of test code for the parent class.
         * <p>
         * Putting all the test code in this inner class (rather than a <code>main</code> method of the parent class) has the following benefits:
         * <ol>
         *  <li>test code is cleanly separated from working code</li>
         *  <li>any <code>main</code> method in the parent class is now reserved for a true program entry point</li>
         *  <li>test code may be easily excluded from the shipping product by removing all the Test class files (e.g. on Windoze, delete all files that end with <code>$Test.class</code>)</li>
         * </ol>
         * Putting all the test code in this inner class (rather than a shadow external class) has the following benefits:
         * <ol>
         *  <li>non-public members may be accessed</li>
         *  <li>the test code lives very close to (so is easy to find) yet is distinct from the working code</li>
         *  <li>there is no need to set up a test package structure</li>
         * </ol>
         public static class Test {
              public static void main(String[] args) throws Exception {
                   Gui gui = new Gui();
                   EventQueue.invokeLater( gui.getBuilder() );
                   new Timer(1000, gui.getTimerActionListener()).start();
              private static class Gui {
                   private Frame frame;
                   private TextField textField;
                   private JFrame jframe;
                   private JLabel jlabel;
                   private JPanel jpanel;
                   private int count = 0;
                   private Runnable getBuilder() {
                        return new Runnable() {
                             public void run() {
                                  System.out.println("Creating a Frame with AWT widgets inside...");
                                  frame = new Frame("ScreenShot.Test.main Frame");
                                  textField = new TextField();
                                  textField.setText( "Waiting for the screen shot process to automatically start..." );
                                  frame.add(textField);                              
                                  frame.pack();
                                  frame.setLocationRelativeTo(null);     // null will center it in the middle of the screen
                                  frame.setVisible(true);
                                  System.out.println("Creating a JFrame with Swing widgets inside...");
                                  jframe = new JFrame("ScreenShot.Test.main JFrame");
                                  jlabel = new JLabel(
                                       "<html>" +
                                            "To be, or not to be: that is the question:" + "<br>" +
                                            "Whether 'tis nobler in the mind to suffer" + "<br>" +
                                            "The slings and arrows of outrageous fortune," + "<br>" +
                                            "Or to take arms against a sea of troubles," + "<br>" +
                                            "And by opposing end them?" + "<br>" +
                                            "To die: to sleep; No more;" + "<br>" +
                                            "and by a sleep to say we end" + "<br>" +
                                            "The heart-ache and the thousand natural shocks" + "<br>" +
                                            "That flesh is heir to," + "<br>" +
                                            "'tis a consummation Devoutly to be wish'd." + "<br>" +
                                       "</html>"
                                  jpanel = new JPanel();
                                  jpanel.setBorder( BorderFactory.createEmptyBorder(20, 20, 20, 20) );
                                  jpanel.add(jlabel);
                                  jframe.getContentPane().add(jpanel);
                                  jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                  jframe.pack();
                                  Point p = frame.getLocation();
                                  p.translate(0, frame.getSize().height  + 10);
                                  jframe.setLocation(p);
                                  jframe.setVisible(true);
                   private ActionListener getTimerActionListener() {
                        return new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  try {
                                       switch (count++) {
                                            case 0:
                                                 displayMessage("Taking a screen shot of the entire desktop...");
                                                 ScreenShot.write( ScreenShot.take(), "desktop.png" );
                                                 break;
                                            case 1:
                                                 displayMessage("Taking a screen shot of the central rectangle of the desktop...");
                                                 Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
                                                 Rectangle region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(region), "desktopCenteredRectangle.png" );
                                                 break;
                                            case 2:
                                                 displayMessage("Taking a screen shot of the TextField...");
                                                 ScreenShot.write( ScreenShot.take(textField), "textField.png" );
                                                 break;
                                            case 3:
                                                 displayMessage("Taking a screen shot of the central rectangle of the TextField...");
                                                 d = textField.getSize();
                                                 region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(textField, region), "textFieldCenteredRectangle.png" );
                                                 break;
                                            case 4:
                                                 displayMessage("Taking a screen shot of the JLabel...");
                                                 ScreenShot.write( ScreenShot.take(jlabel), "jlabel.png" );
                                                 break;
                                            case 5:
                                                 displayMessage("Taking a screen shot of the central rectangle of the JLabel...");
                                                 d = jpanel.getSize();
                                                 region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(jpanel, region), "jpanelCenteredRectangle.png" );
                                                 break;
                                            default:
                                                 System.exit(0);
                                                 break;
                                  catch (Throwable t) {
                                       t.printStackTrace(System.err);
                             private void displayMessage(String text) {
                                  System.out.println(text);
                                  textField.setText(text);
                                  frame.pack();
                                  frame.invalidate();
                             private Rectangle getCenteredRectangle(Dimension d) {
                                  int x = d.width / 4;
                                  int y = d.height / 4;
                                  int width = d.width / 2;
                                  int height = d.height / 2;
                                  return new Rectangle(x, y, width, height);
    }

  • How to save VISA information into a configuration file

    Hi guys,
    I've got a problem that i can't quite figure out and I'm sure someone else has done this but i have searched the forums and didn't find anything suitable myself.
    I'm trying to save configuration files for my program and then reload them back in so that i can get the same state of the controls.  One of the controls I'd like to save into the configuration file is a VISA control.  has anyone figured out how to save this into configuration files?  I know that OpenG has a write variant to config but Id like to stay away from 3rd party stuff as much as possible.  Does anyone have any suggestions as to how to get around this?
    Thanks
    Brent 
    Solved!
    Go to Solution.

    The alternative to Write Keys, if you don't want a text file, is a BIN file. I do it this way when I don't want users poking around text file trying to change things, and/or for security. And it's fast.
    The attached picture shows, in general, how to do it.
    Richard
    Attachments:
    saveSettings.gif ‏11 KB

  • ImageIO.write to save as GIF file

    I have been use ImageIO.write and BufferedImage to save current Panel's paint(). with transparency.
    BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    components[0].paint(g2);
    g2.dispose();
    final File file = new File(save_File, "tt.png");
    ImageIO.write(image, "png", file);success at PNG with transparency.
    but now I want to save as GIF file,not png.
    but I change png -> gif
    final File file = new File(save_File, "tt.gif");
    ImageIO.write(image, "gif", file);it will be all black color picture.
    Why?
    And how can I success to do this.

    GIF doen't do well for transparent images. For transparent images, you can find total solutions from this theread, including the reasons why gif doen't work;
    http://forum.java.sun.com/thread.jspa?threadID=5227456

Maybe you are looking for

  • Creating a Folder Within Form or Document Library & Display the name not in the name column.

    I have created a form library that will used to create folders within that. The folder creation is done using an InfoPath Form that has been uploaded to the Form Library. When the new folder was created the name will be displayed at the Name column w

  • Error : The iphone  cannot be synced. The required file cant be found

    I am getting this error when i try to sync my photo's from iphoto. Never had this issue but its not syncing any photo's any suggestions or cures? Use iphone 3GS with MBP (late 2008)

  • HP Pro L7680 all-in-one printing extra blank pages

    No matter what I print the printer adds a blank page before and after each print job. Doesn't matter application amd I don't see it on fax, scans or copies. Thi shappened after my laptop had to be wiped and reloaded. I reloaded the drivers and has ha

  • N97 Mini Available

    Just seen a TV advert for the new N97 mini and it was advertised as available on Vodafone.  Checking the Nokia UK website, it no longer says available for pre-order and is available. No sign of availability on the N900 yet though, still pre-order onl

  • Cannot open photoshop

    Hi, I am using my Mac Pro with photoshop. My trial of Photoshop CS6 Extended had ran out, so I buy Creative Cloud today and want to change for it. However, after I bought CC online, I try to open my photoshop, but it still shows that my trial is over