Rectangle 27 1

ImageIO
BufferedImage
BufferedImage image; // your image
OutputStream stream; // your output

try {
    ImageIO.write(image, "png", stream);
}
finally {
    stream.flush();
}

Where stream can be a FileOutputStream to the server's file system, the OutputStream of a database blob, or the servlet response's OutputStream, depending on where/if you want to store it.

java - Converting Buffered Image to MultipartFile - Stack Overflow

java image spring spring-mvc
Rectangle 27 47

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

I used your above code. I am working on java web services where i am getting base64 string of uploaded image form IOS device. When i tried your above code in separate application i get original image as it is. But when i tried it with web services image is not created. When i debug application in both cases the byte array for same base64 string is different in length. Why i am getting this problem.

@Aniket: That doesn't give nearly enough information for us to help you. I suggest you ask a new question with more context - what the web service is, how it's implemented, how you're uploading the image data, what you've observed etc.

java - Write Base64-encoded image to file - Stack Overflow

java image base64 decode encode
Rectangle 27 10

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

How would I use this? Do I place it in a JLabel?

@Aaron That would depend on your ultimate goal and how much control you need. Yes and JLabel would be the simplest solution. See updates

Wow, that edit was very helpful! Ill check out the links now

Nice to have helped :)

java - JFrame background image - Stack Overflow

java swing background jframe
Rectangle 27 10

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

How would I use this? Do I place it in a JLabel?

@Aaron That would depend on your ultimate goal and how much control you need. Yes and JLabel would be the simplest solution. See updates

Wow, that edit was very helpful! Ill check out the links now

Nice to have helped :)

java - JFrame background image - Stack Overflow

java swing background jframe
Rectangle 27 21

Your problem is that ImageIO is misinterpreting the YCbCr data in your JPEG as RBG data. The relevant Java bugs are 4712797 and 4776576, which Oracle wrongly claims were fixed in Java 1.4, but in reality still afflict some Java 5, 6, and 7 JVMs.

In a project I work on, we've dealt with this problem by loading a specially-constructed test JPEG with a single black pixel to see if ImageIO loads it properly. If the pixel comes up green, then ImageIO is misinterpreting the image data, so when we load JPEGs later and we detect the sort of JPEG which causes the problem, we also apply a color correction. (The kind of JPEG which triggers the problem in JVMs which exhibit it has a particular kind of subsampling and no JFIF marker.)

Here's some LGPLv2-licensed code which deals with the problem. The need for code like this to work around dozen-year-old bugs when the whole rest of the world manages to load JPEGs properly is one of the reasons I want Java to die in a fire.

Still not fixed - I'm seeing this problem on Java 8.

java - jpeg image color gets drastically changed after just ImageIO.re...

java image image-processing
Rectangle 27 4

An empty iterator usually means ImageIO hasn't found a good image reader for decoding your image. This may be because you'are missing the right decoder in your classpath, or you image has an unsupported color model.

javax.imageio - Detecting image encoding in Java - Stack Overflow

java javax.imageio
Rectangle 27 3

Old Code - before I realized this was about images

Try using a JToggleButton instead. No need for a MouseListener, and responds to keyboard input.

import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
import java.awt.Image;

class ToggleImage {
    public static void main(String[] args) throws Exception {
        URL url1 = new URL("http://pscode.org/media/stromlo1.jpg");
        URL url2 = new URL("http://pscode.org/media/stromlo2.jpg");

        final Image image1 = ImageIO.read(url1);
        final Image image2 = ImageIO.read(url2);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JToggleButton button = new JToggleButton();
                button.setIcon(new ImageIcon(image1));
                button.setSelectedIcon(new ImageIcon(image2));
                button.setBorderPainted(false);
                button.setContentAreaFilled(false);

                JOptionPane.showMessageDialog(null, button);
            }
        });
    }
}

I want to make it so that if I click on the JLabel

What about for people who are 'mouse challenged? Use a JTextField instead. Tab to any link and hit Enter to activate.

import java.awt.Desktop;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridLayout;

import java.awt.event.*;

import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import javax.swing.border.MatteBorder;
import javax.swing.border.Border;

import java.net.URI;
import java.io.File;

/**
A Java 1.6+ LinkLabel that uses the Desktop class for opening
the document of interest.

The Desktop.browse(URI) method can be invoked from applications,
applets and apps. launched using Java Webstart.  In the latter
two cases, the usual fall-back methods are used for sandboxed apps
(see the JavaDocs for further details).

While called a 'label', this class actually extends JTextField,
to easily allow the component to become focusable using keyboard
navigation.

To successfully browse to a URI for a local File, the file name
must be constructed using a canonical path.

@author Andrew Thompson
@version 2008/08/23
*/
public class LinkLabel
    // we extend a JTextField, to get a focusable component
    extends JTextField
    implements MouseListener, FocusListener, ActionListener {

    /** The target or href of this link. */
    private URI target;

    public Color standardColor = new Color(0,0,255);
    public Color hoverColor = new Color(255,0,0);
    public Color activeColor = new Color(128,0,128);
    public Color transparent = new Color(0,0,0,0);

    public boolean underlineVisible = true;

    private Border activeBorder;
    private Border hoverBorder;
    private Border standardBorder;

    /** Construct a LinkLabel that points to the given target.
    The URI will be used as the link text.*/
    public LinkLabel(URI target) {
        this( target, target.toString() );
    }

    /** Construct a LinkLabel that points to the given target,
    and displays the text to the user. */
    public LinkLabel(URI target, String text) {
        super(text);
        this.target = target;
    }

    /* Set the active color for this link (default is purple). */
    public void setActiveColor(Color active) {
        activeColor = active;
    }

    /* Set the hover/focused color for this link (default is red). */
    public void setHoverColor(Color hover) {
        hoverColor = hover;
    }

    /* Set the standard (non-focused, non-active) color for this
    link (default is blue). */
    public void setStandardColor(Color standard) {
        standardColor = standard;
    }

    /** Determines whether the */
    public void setUnderlineVisible(boolean underlineVisible) {
        this.underlineVisible = underlineVisible;
    }

    /* Add the listeners, configure the field to look and act
    like a link. */
    public void init() {
        this.addMouseListener(this);
        this.addFocusListener(this);
        this.addActionListener(this);
        setToolTipText(target.toString());

        if (underlineVisible) {
            activeBorder = new MatteBorder(0,0,1,0,activeColor);
            hoverBorder = new MatteBorder(0,0,1,0,hoverColor);
            standardBorder = new MatteBorder(0,0,1,0,transparent);
        } else {
            activeBorder = new MatteBorder(0,0,0,0,activeColor);
            hoverBorder = new MatteBorder(0,0,0,0,hoverColor);
            standardBorder = new MatteBorder(0,0,0,0,transparent);
        }

        // make it appear like a label/link
        setEditable(false);
        setForeground(standardColor);
        setBorder(standardBorder);
        setCursor( new Cursor(Cursor.HAND_CURSOR) );
    }

    /** Browse to the target URI using the Desktop.browse(URI)
    method.  For visual indication, change to the active color
    at method start, and return to the standard color once complete.
    This is usually so fast that the active color does not appear,
    but it will take longer if there is a problem finding/loading
    the browser or URI (e.g. for a File). */
    public void browse() {
        setForeground(activeColor);
        setBorder(activeBorder);
        try {
            Desktop.getDesktop().browse(target);
        } catch(Exception e) {
            e.printStackTrace();
        }
        setForeground(standardColor);
        setBorder(standardBorder);
    }

    /** Browse to the target. */
    public void actionPerformed(ActionEvent ae) {
        browse();
    }

    /** Browse to the target. */
    public void mouseClicked(MouseEvent me) {
        browse();
    }

    /** Set the color to the hover color. */
    public void mouseEntered(MouseEvent me) {
        setForeground(hoverColor);
        setBorder(hoverBorder);
    }

    /** Set the color to the standard color. */
    public void mouseExited(MouseEvent me) {
        setForeground(standardColor);
        setBorder(standardBorder);
    }

    public void mouseReleased(MouseEvent me) {}

    public void mousePressed(MouseEvent me) {}

    /** Set the color to the standard color. */
    public void focusLost(FocusEvent fe) {
        setForeground(standardColor);
        setBorder(standardBorder);
    }

    /** Set the color to the hover color. */
    public void focusGained(FocusEvent fe) {
        setForeground(hoverColor);
        setBorder(hoverBorder);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    File f = new File(".","LinkLabel.java");

                    /* Filename must be constructed with a canonical path in
                    order to successfully use Desktop.browse(URI)! */
                    f = new File(f.getCanonicalPath());

                    JPanel p = new JPanel(new GridLayout(0,1));

                    URI uriFile = f.toURI();

                    LinkLabel linkLabelFile = new LinkLabel(uriFile);
                    linkLabelFile.init();
                    p.add(linkLabelFile);

                    LinkLabel linkLabelWeb = new LinkLabel(
                        new URI("http://pscode.org/sscce.html"),
                        "SSCCE");
                    linkLabelWeb.setStandardColor(new Color(0,128,0));
                    linkLabelWeb.setHoverColor(new Color(222,128,0));
                    linkLabelWeb.init();

                    /* This shows a quirk of the LinkLabel class, the
                    size of the text field needs to be constrained to
                    get the underline to appear properly. */
                    p.add(linkLabelWeb);

                    LinkLabel linkLabelConstrain = new LinkLabel(
                        new URI("http://stackoverflow.com/"),
                        "Stack Overflow");
                    linkLabelConstrain.init();
                    /* ..and this shows one way to constrain the size
                    (appropriate for this layout).
                    Similar tricks can be used to ensure the underline does
                    not drop too far *below* the link (think BorderLayout
                    NORTH/SOUTH).
                    The same technique can also be nested further to produce
                    a NORTH+EAST packing (for example). */
                    JPanel labelConstrain = new JPanel(new BorderLayout());
                    labelConstrain.add( linkLabelConstrain, BorderLayout.EAST );
                    p.add(labelConstrain);

                    LinkLabel linkLabelNoUnderline = new LinkLabel(
                        new URI("http://java.net/"),
                        "java.net");
                    // another way to deal with the underline is to remove it
                    linkLabelNoUnderline.setUnderlineVisible(false);
                    // we can use the methods inherited from JTextField
                    linkLabelNoUnderline.
                        setHorizontalAlignment(JTextField.CENTER);
                    linkLabelNoUnderline.init();
                    p.add(linkLabelNoUnderline);

                    JOptionPane.showMessageDialog( null, p );
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

@mKorbel I edited the code (after first deleting the answer!) to use a toggle button when I realized this was about images. ;)

my curiosity about, question to your attn. picture that someone head with cap or astronomic observatory or ???...

@mKorbel: stromlo1.jpg is the 1st shot of a Time Lapse Animation that I caught from Mount Stromlo near Canberra in Australia. It has observatories. That one is for Ifrared mapping AFAIR. The shot shown here is the last shot in that series - with Venus in the BG. You can see the TLA as Mount Stromlo Sunset at DrewTubeish. ( & thanks for asking ;)

phaaa that would be great job working inside full-steel mushroom and maybe job for helicopter owner, imaging that ..., really its time to stop drinking, take dr*** and then look around with clear head

java - How do I create an event handler for a JLabel? - Stack Overflow

java swing jlabel mouselistener
Rectangle 27 23

The URLConnection#guessContentTypeFromStream() or ...FromName() is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagic which does its work better than URLConnection#guessXXX() methods.

String mimeType = Magic.getMagicMatch(file, false).getMimeType();

This supports a more wide range of mime types.

@BalusC i tried to use it but with docx files it returns that the mime type is application/zip which is not correct

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

image - Best way to determine mime type of a file in java? - Stack Ove...

java image mime-types
Rectangle 27 23

The URLConnection#guessContentTypeFromStream() or ...FromName() is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagic which does its work better than URLConnection#guessXXX() methods.

String mimeType = Magic.getMagicMatch(file, false).getMimeType();

This supports a more wide range of mime types.

@BalusC i tried to use it but with docx files it returns that the mime type is application/zip which is not correct

image - Best way to determine mime type of a file in java? - Stack Ove...

java image mime-types
Rectangle 27 5

I have solved the problem by using ImageIO

try {
    BufferedImage bufImg=ImageIO.read(new File("d:\\img.png"));
    jlabel.setIcon(new ImageIcon(bufImg));
    //jlabel.repaint();
    //works even without repaint
}
catch (IOException ex) {
    System.out.println("Unable to read image file");
}
ImageIcon img=new ImageIcon("D:\\img.png");
img.getImage().flush();
jlabel.setIcon(img);

Also you can note that

ImageIO
img.getImage().flush();
  • but if I have different file name every time no need to call img.getImage().flush(); only go on jlabel.setIcon(img); and image is not flickering.

The images used by the application, will later become part of it on deployment, and hence refer to as embedded resource. Then it would be wise, to access them in terms of a URL instead of a File. Don't use Absolute Path instead use Relative Path with respect to the .class/package, using ClassName.class.getResource("/pathToImage/image.extension"), as shown in the info of embedded-resource, do watch the links provided on the info page. For the rest You're MOST WELCOME and KEEP SMILING :-)

but don't know what is problem with setIcon(). Any one know? - What problem? The image is cached so you need to create a new Icon as was demonstrated by mKobel's answer.

@nIcE cOw: I know this thing but my problem was to get external image, may be download from web and write in temp on same file. then show

@aquestion : Actually ImageIO.read() blocks the flow, till the image is loaded, hence if the images you are trying to display are larger in size, try to do that task in the background using SwingWorker, as shown in this example

java - Refresh Same Image in a JLabel - Stack Overflow

java swing jlabel imageicon
Rectangle 27 5

I have solved the problem by using ImageIO

try {
    BufferedImage bufImg=ImageIO.read(new File("d:\\img.png"));
    jlabel.setIcon(new ImageIcon(bufImg));
    //jlabel.repaint();
    //works even without repaint
}
catch (IOException ex) {
    System.out.println("Unable to read image file");
}
ImageIcon img=new ImageIcon("D:\\img.png");
img.getImage().flush();
jlabel.setIcon(img);

Also you can note that

ImageIO
img.getImage().flush();
  • but if I have different file name every time no need to call img.getImage().flush(); only go on jlabel.setIcon(img); and image is not flickering.

The images used by the application, will later become part of it on deployment, and hence refer to as embedded resource. Then it would be wise, to access them in terms of a URL instead of a File. Don't use Absolute Path instead use Relative Path with respect to the .class/package, using ClassName.class.getResource("/pathToImage/image.extension"), as shown in the info of embedded-resource, do watch the links provided on the info page. For the rest You're MOST WELCOME and KEEP SMILING :-)

but don't know what is problem with setIcon(). Any one know? - What problem? The image is cached so you need to create a new Icon as was demonstrated by mKobel's answer.

@nIcE cOw: I know this thing but my problem was to get external image, may be download from web and write in temp on same file. then show

@aquestion : Actually ImageIO.read() blocks the flow, till the image is loaded, hence if the images you are trying to display are larger in size, try to do that task in the background using SwingWorker, as shown in this example

java - Refresh Same Image in a JLabel - Stack Overflow

java swing jlabel imageicon
Rectangle 27 69

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;

import javax.swing.*;

import javax.swing.border.TitledBorder;

import javax.imageio.ImageIO;

import java.io.File;

/**
Create a screenshot of a component.
@author Andrew Thompson
*/
class ComponentImageCapture {

  static final String HELP =
    "Type Ctrl-0 to get a screenshot of the current GUI.\n" +
    "The screenshot will be saved to the current " +
    "directory as 'screenshot.png'.";

  public static BufferedImage getScreenShot(
    Component component) {

    BufferedImage image = new BufferedImage(
      component.getWidth(),
      component.getHeight(),
      BufferedImage.TYPE_INT_RGB
      );
    // call the Component's paint method, using
    // the Graphics object of the image.
    component.paint( image.getGraphics() ); // alternately use .printAll(..)
    return image;
  }

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        final JFrame f = new JFrame("Test Screenshot");

        JMenuItem screenshot =
          new JMenuItem("Screenshot");
        screenshot.setAccelerator(
          KeyStroke.getKeyStroke(
            KeyEvent.VK_0,
            InputEvent.CTRL_DOWN_MASK
          ));
        screenshot.addActionListener(
          new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
              BufferedImage img = getScreenShot(
                f.getContentPane() );
              JOptionPane.showMessageDialog(
                null,
                new JLabel(
                  new ImageIcon(
                    img.getScaledInstance(
                      img.getWidth(null)/2,
                      img.getHeight(null)/2,
                      Image.SCALE_SMOOTH )
                    )));
              try {
                // write the image as a PNG
                ImageIO.write(
                  img,
                  "png",
                  new File("screenshot.png"));
              } catch(Exception e) {
                e.printStackTrace();
              }
            }
          } );
        JMenu menu = new JMenu("Other");
        menu.add(screenshot);
        JMenuBar mb = new JMenuBar();
        mb.add(menu);
        f.setJMenuBar(mb);

        JPanel p = new JPanel( new BorderLayout(5,5) );
        p.setBorder( new TitledBorder("Main GUI") );
        p.add( new JScrollPane(new JTree()),
          BorderLayout.WEST );
        p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
          BorderLayout.CENTER );

        f.setContentPane( p );
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

The code shown above presumes the component has been realized on-screen, prior to rendering.

Rob Camick shows how to paint an unrealized component in the Screen Image class.

Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.

Here is an updated variant of the code shown on the second link.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {

            String title = "<html><body style='width: 200px; padding: 5px;'>"
                + "<h1>Do U C Me?</h1>"
                + "Here is a long string that will wrap.  "
                + "The effect we want is a multi-line label.";

                JFrame f = new JFrame("Label Render Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                BufferedImage image = new BufferedImage(
                    400,
                    300,
                    BufferedImage.TYPE_INT_RGB);
                Graphics2D imageGraphics = image.createGraphics();
                GradientPaint gp = new GradientPaint(
                    20f,
                    20f,
                    Color.red,
                    380f,
                    280f,
                    Color.orange);
                imageGraphics.setPaint(gp);
                imageGraphics.fillRect(0, 0, 400, 300);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());

                Dimension d = textLabel.getPreferredSize();
                BufferedImage bi = new BufferedImage(
                    d.width,
                    d.height,
                    BufferedImage.TYPE_INT_ARGB);
                Graphics g = bi.createGraphics();
                g.setColor(new Color(255, 255, 255, 128));
                g.fillRoundRect(
                    0,
                    0,
                    bi.getWidth(f),
                    bi.getHeight(f),
                    15,
                    10);
                g.setColor(Color.black);
                textLabel.paint(g);
                Graphics g2 = image.getGraphics();
                g2.drawImage(bi, 20, 20, f);

                ImageIcon ii = new ImageIcon(image);
                JLabel imageLabel = new JLabel(ii);

                f.getContentPane().add(imageLabel);
                f.pack();
                f.setLocationByPlatform(true);

                f.setVisible(true);
            }
        });
    }
}

+1 @Andrew : Thanks for the answer, this is certainly better than using the robot. H/w component.paint( image.getGraphics() ); still involves making a copy of the Image. I was looking for a way to obtain the Image directly from the buffer, if indeed that were possible. I'll accept your answer if no-one else answers with this!

just curious: why the p.validate?

@kleopatra: The best explanation I can think of (wrote that code a long while ago) is that my first attempts were obtaining an image of the component before it was realized. As far as I can infer, that did not work. Removed that line, added the 'See also' section that addresses that corner case.

I have a doubt. I tried removing the label.setSize() method, the text on the JLabel didn't appear? Why did this happen? (Thank you. +1)

print or printAll instead of paint would be more efficient as they're not double buffered

java - Swing: Obtain Image of JFrame - Stack Overflow

java image swing screenshot jframe
Rectangle 27 69

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;

import javax.swing.*;

import javax.swing.border.TitledBorder;

import javax.imageio.ImageIO;

import java.io.File;

/**
Create a screenshot of a component.
@author Andrew Thompson
*/
class ComponentImageCapture {

  static final String HELP =
    "Type Ctrl-0 to get a screenshot of the current GUI.\n" +
    "The screenshot will be saved to the current " +
    "directory as 'screenshot.png'.";

  public static BufferedImage getScreenShot(
    Component component) {

    BufferedImage image = new BufferedImage(
      component.getWidth(),
      component.getHeight(),
      BufferedImage.TYPE_INT_RGB
      );
    // call the Component's paint method, using
    // the Graphics object of the image.
    component.paint( image.getGraphics() ); // alternately use .printAll(..)
    return image;
  }

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        final JFrame f = new JFrame("Test Screenshot");

        JMenuItem screenshot =
          new JMenuItem("Screenshot");
        screenshot.setAccelerator(
          KeyStroke.getKeyStroke(
            KeyEvent.VK_0,
            InputEvent.CTRL_DOWN_MASK
          ));
        screenshot.addActionListener(
          new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
              BufferedImage img = getScreenShot(
                f.getContentPane() );
              JOptionPane.showMessageDialog(
                null,
                new JLabel(
                  new ImageIcon(
                    img.getScaledInstance(
                      img.getWidth(null)/2,
                      img.getHeight(null)/2,
                      Image.SCALE_SMOOTH )
                    )));
              try {
                // write the image as a PNG
                ImageIO.write(
                  img,
                  "png",
                  new File("screenshot.png"));
              } catch(Exception e) {
                e.printStackTrace();
              }
            }
          } );
        JMenu menu = new JMenu("Other");
        menu.add(screenshot);
        JMenuBar mb = new JMenuBar();
        mb.add(menu);
        f.setJMenuBar(mb);

        JPanel p = new JPanel( new BorderLayout(5,5) );
        p.setBorder( new TitledBorder("Main GUI") );
        p.add( new JScrollPane(new JTree()),
          BorderLayout.WEST );
        p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
          BorderLayout.CENTER );

        f.setContentPane( p );
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

The code shown above presumes the component has been realized on-screen, prior to rendering.

Rob Camick shows how to paint an unrealized component in the Screen Image class.

Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.

Here is an updated variant of the code shown on the second link.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {

            String title = "<html><body style='width: 200px; padding: 5px;'>"
                + "<h1>Do U C Me?</h1>"
                + "Here is a long string that will wrap.  "
                + "The effect we want is a multi-line label.";

                JFrame f = new JFrame("Label Render Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                BufferedImage image = new BufferedImage(
                    400,
                    300,
                    BufferedImage.TYPE_INT_RGB);
                Graphics2D imageGraphics = image.createGraphics();
                GradientPaint gp = new GradientPaint(
                    20f,
                    20f,
                    Color.red,
                    380f,
                    280f,
                    Color.orange);
                imageGraphics.setPaint(gp);
                imageGraphics.fillRect(0, 0, 400, 300);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());

                Dimension d = textLabel.getPreferredSize();
                BufferedImage bi = new BufferedImage(
                    d.width,
                    d.height,
                    BufferedImage.TYPE_INT_ARGB);
                Graphics g = bi.createGraphics();
                g.setColor(new Color(255, 255, 255, 128));
                g.fillRoundRect(
                    0,
                    0,
                    bi.getWidth(f),
                    bi.getHeight(f),
                    15,
                    10);
                g.setColor(Color.black);
                textLabel.paint(g);
                Graphics g2 = image.getGraphics();
                g2.drawImage(bi, 20, 20, f);

                ImageIcon ii = new ImageIcon(image);
                JLabel imageLabel = new JLabel(ii);

                f.getContentPane().add(imageLabel);
                f.pack();
                f.setLocationByPlatform(true);

                f.setVisible(true);
            }
        });
    }
}

+1 @Andrew : Thanks for the answer, this is certainly better than using the robot. H/w component.paint( image.getGraphics() ); still involves making a copy of the Image. I was looking for a way to obtain the Image directly from the buffer, if indeed that were possible. I'll accept your answer if no-one else answers with this!

just curious: why the p.validate?

@kleopatra: The best explanation I can think of (wrote that code a long while ago) is that my first attempts were obtaining an image of the component before it was realized. As far as I can infer, that did not work. Removed that line, added the 'See also' section that addresses that corner case.

I have a doubt. I tried removing the label.setSize() method, the text on the JLabel didn't appear? Why did this happen? (Thank you. +1)

print or printAll instead of paint would be more efficient as they're not double buffered

java - Swing: Obtain Image of JFrame - Stack Overflow

java image swing screenshot jframe
Rectangle 27 69

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;

import javax.swing.*;

import javax.swing.border.TitledBorder;

import javax.imageio.ImageIO;

import java.io.File;

/**
Create a screenshot of a component.
@author Andrew Thompson
*/
class ComponentImageCapture {

  static final String HELP =
    "Type Ctrl-0 to get a screenshot of the current GUI.\n" +
    "The screenshot will be saved to the current " +
    "directory as 'screenshot.png'.";

  public static BufferedImage getScreenShot(
    Component component) {

    BufferedImage image = new BufferedImage(
      component.getWidth(),
      component.getHeight(),
      BufferedImage.TYPE_INT_RGB
      );
    // call the Component's paint method, using
    // the Graphics object of the image.
    component.paint( image.getGraphics() ); // alternately use .printAll(..)
    return image;
  }

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        final JFrame f = new JFrame("Test Screenshot");

        JMenuItem screenshot =
          new JMenuItem("Screenshot");
        screenshot.setAccelerator(
          KeyStroke.getKeyStroke(
            KeyEvent.VK_0,
            InputEvent.CTRL_DOWN_MASK
          ));
        screenshot.addActionListener(
          new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
              BufferedImage img = getScreenShot(
                f.getContentPane() );
              JOptionPane.showMessageDialog(
                null,
                new JLabel(
                  new ImageIcon(
                    img.getScaledInstance(
                      img.getWidth(null)/2,
                      img.getHeight(null)/2,
                      Image.SCALE_SMOOTH )
                    )));
              try {
                // write the image as a PNG
                ImageIO.write(
                  img,
                  "png",
                  new File("screenshot.png"));
              } catch(Exception e) {
                e.printStackTrace();
              }
            }
          } );
        JMenu menu = new JMenu("Other");
        menu.add(screenshot);
        JMenuBar mb = new JMenuBar();
        mb.add(menu);
        f.setJMenuBar(mb);

        JPanel p = new JPanel( new BorderLayout(5,5) );
        p.setBorder( new TitledBorder("Main GUI") );
        p.add( new JScrollPane(new JTree()),
          BorderLayout.WEST );
        p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
          BorderLayout.CENTER );

        f.setContentPane( p );
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

The code shown above presumes the component has been realized on-screen, prior to rendering.

Rob Camick shows how to paint an unrealized component in the Screen Image class.

Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.

Here is an updated variant of the code shown on the second link.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {

            String title = "<html><body style='width: 200px; padding: 5px;'>"
                + "<h1>Do U C Me?</h1>"
                + "Here is a long string that will wrap.  "
                + "The effect we want is a multi-line label.";

                JFrame f = new JFrame("Label Render Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                BufferedImage image = new BufferedImage(
                    400,
                    300,
                    BufferedImage.TYPE_INT_RGB);
                Graphics2D imageGraphics = image.createGraphics();
                GradientPaint gp = new GradientPaint(
                    20f,
                    20f,
                    Color.red,
                    380f,
                    280f,
                    Color.orange);
                imageGraphics.setPaint(gp);
                imageGraphics.fillRect(0, 0, 400, 300);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());

                Dimension d = textLabel.getPreferredSize();
                BufferedImage bi = new BufferedImage(
                    d.width,
                    d.height,
                    BufferedImage.TYPE_INT_ARGB);
                Graphics g = bi.createGraphics();
                g.setColor(new Color(255, 255, 255, 128));
                g.fillRoundRect(
                    0,
                    0,
                    bi.getWidth(f),
                    bi.getHeight(f),
                    15,
                    10);
                g.setColor(Color.black);
                textLabel.paint(g);
                Graphics g2 = image.getGraphics();
                g2.drawImage(bi, 20, 20, f);

                ImageIcon ii = new ImageIcon(image);
                JLabel imageLabel = new JLabel(ii);

                f.getContentPane().add(imageLabel);
                f.pack();
                f.setLocationByPlatform(true);

                f.setVisible(true);
            }
        });
    }
}

+1 @Andrew : Thanks for the answer, this is certainly better than using the robot. H/w component.paint( image.getGraphics() ); still involves making a copy of the Image. I was looking for a way to obtain the Image directly from the buffer, if indeed that were possible. I'll accept your answer if no-one else answers with this!

just curious: why the p.validate?

@kleopatra: The best explanation I can think of (wrote that code a long while ago) is that my first attempts were obtaining an image of the component before it was realized. As far as I can infer, that did not work. Removed that line, added the 'See also' section that addresses that corner case.

I have a doubt. I tried removing the label.setSize() method, the text on the JLabel didn't appear? Why did this happen? (Thank you. +1)

print or printAll instead of paint would be more efficient as they're not double buffered

java - Swing: Obtain Image of JFrame - Stack Overflow

java image swing screenshot jframe
Rectangle 27 69

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;

import javax.swing.*;

import javax.swing.border.TitledBorder;

import javax.imageio.ImageIO;

import java.io.File;

/**
Create a screenshot of a component.
@author Andrew Thompson
*/
class ComponentImageCapture {

  static final String HELP =
    "Type Ctrl-0 to get a screenshot of the current GUI.\n" +
    "The screenshot will be saved to the current " +
    "directory as 'screenshot.png'.";

  public static BufferedImage getScreenShot(
    Component component) {

    BufferedImage image = new BufferedImage(
      component.getWidth(),
      component.getHeight(),
      BufferedImage.TYPE_INT_RGB
      );
    // call the Component's paint method, using
    // the Graphics object of the image.
    component.paint( image.getGraphics() ); // alternately use .printAll(..)
    return image;
  }

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        final JFrame f = new JFrame("Test Screenshot");

        JMenuItem screenshot =
          new JMenuItem("Screenshot");
        screenshot.setAccelerator(
          KeyStroke.getKeyStroke(
            KeyEvent.VK_0,
            InputEvent.CTRL_DOWN_MASK
          ));
        screenshot.addActionListener(
          new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
              BufferedImage img = getScreenShot(
                f.getContentPane() );
              JOptionPane.showMessageDialog(
                null,
                new JLabel(
                  new ImageIcon(
                    img.getScaledInstance(
                      img.getWidth(null)/2,
                      img.getHeight(null)/2,
                      Image.SCALE_SMOOTH )
                    )));
              try {
                // write the image as a PNG
                ImageIO.write(
                  img,
                  "png",
                  new File("screenshot.png"));
              } catch(Exception e) {
                e.printStackTrace();
              }
            }
          } );
        JMenu menu = new JMenu("Other");
        menu.add(screenshot);
        JMenuBar mb = new JMenuBar();
        mb.add(menu);
        f.setJMenuBar(mb);

        JPanel p = new JPanel( new BorderLayout(5,5) );
        p.setBorder( new TitledBorder("Main GUI") );
        p.add( new JScrollPane(new JTree()),
          BorderLayout.WEST );
        p.add( new JScrollPane( new JTextArea(HELP,10,30) ),
          BorderLayout.CENTER );

        f.setContentPane( p );
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

The code shown above presumes the component has been realized on-screen, prior to rendering.

Rob Camick shows how to paint an unrealized component in the Screen Image class.

Rob Camick addresses the problem of painting an unrealized component in the Screen Image class.

Another thread that might be of relevance, is Render JLabel without 1st displaying, particularly the 'one line fix' by Darryl Burke.

Here is an updated variant of the code shown on the second link.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {

            String title = "<html><body style='width: 200px; padding: 5px;'>"
                + "<h1>Do U C Me?</h1>"
                + "Here is a long string that will wrap.  "
                + "The effect we want is a multi-line label.";

                JFrame f = new JFrame("Label Render Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                BufferedImage image = new BufferedImage(
                    400,
                    300,
                    BufferedImage.TYPE_INT_RGB);
                Graphics2D imageGraphics = image.createGraphics();
                GradientPaint gp = new GradientPaint(
                    20f,
                    20f,
                    Color.red,
                    380f,
                    280f,
                    Color.orange);
                imageGraphics.setPaint(gp);
                imageGraphics.fillRect(0, 0, 400, 300);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());

                Dimension d = textLabel.getPreferredSize();
                BufferedImage bi = new BufferedImage(
                    d.width,
                    d.height,
                    BufferedImage.TYPE_INT_ARGB);
                Graphics g = bi.createGraphics();
                g.setColor(new Color(255, 255, 255, 128));
                g.fillRoundRect(
                    0,
                    0,
                    bi.getWidth(f),
                    bi.getHeight(f),
                    15,
                    10);
                g.setColor(Color.black);
                textLabel.paint(g);
                Graphics g2 = image.getGraphics();
                g2.drawImage(bi, 20, 20, f);

                ImageIcon ii = new ImageIcon(image);
                JLabel imageLabel = new JLabel(ii);

                f.getContentPane().add(imageLabel);
                f.pack();
                f.setLocationByPlatform(true);

                f.setVisible(true);
            }
        });
    }
}

+1 @Andrew : Thanks for the answer, this is certainly better than using the robot. H/w component.paint( image.getGraphics() ); still involves making a copy of the Image. I was looking for a way to obtain the Image directly from the buffer, if indeed that were possible. I'll accept your answer if no-one else answers with this!

just curious: why the p.validate?

@kleopatra: The best explanation I can think of (wrote that code a long while ago) is that my first attempts were obtaining an image of the component before it was realized. As far as I can infer, that did not work. Removed that line, added the 'See also' section that addresses that corner case.

I have a doubt. I tried removing the label.setSize() method, the text on the JLabel didn't appear? Why did this happen? (Thank you. +1)

print or printAll instead of paint would be more efficient as they're not double buffered

@JavaTechnical The size of a label is typically set (appropriate to the layout) when the code calls pack() or validate(). Those methods will often base the size on the preferred size. Because no layouts are involved here, we need to set the size explicitly. More info. in the Oracle thread linked in the answer.

java - Swing: Obtain Image of JFrame - Stack Overflow

java image swing screenshot jframe
Rectangle 27 4

You don't need to use JAI. I would recommend you use the normal ImageIO API and a TIFF plugin.

There are several TIFF plugins for ImageIO available, and depending on your needs, you could use the one from jai-imageio, my TIFF plugin or some other third-party plugin.

My plugin supports most common types of TIFFs. In contrast to jai-imageio, no native libs are required. You can either add Maven dependencies to your project or download directly from this link.

The good thing about using the ImageIO API, is that after you have the plugins properly installed, all you need to do is:

BufferedImage img = ImageIO.read("pics/img"+i+".tif");

Worked instantely after simply adding to the pom.xml (from Maven Central). Even with 16 bit TIFF images. Good work, thank you!

Java Handling TIF Images - Stack Overflow

java image tiff javax.imageio
Rectangle 27 482

If you are using JPanels, then are probably working with Swing. Try this:

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);

The image is now a swing component. It becomes subject to layout conditions like any other component.

how to scale the image according to the size of the JLabel?

Nice code! I'm not much experienced with Swing but I can't get it work. Does anybody tried it in jdk 1.6.0_16?

@ATorras I know you asked this a while back but if any other newbies had my issues, remember to picLabel.setBounds();

you answered it 2 years after it was asked and got more upvotes than the accepted answer. congrats, and nice code

java - How to add an image to a JPanel? - Stack Overflow

java image swing jpanel
Rectangle 27 482

If you are using JPanels, then are probably working with Swing. Try this:

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);

The image is now a swing component. It becomes subject to layout conditions like any other component.

how to scale the image according to the size of the JLabel?

Nice code! I'm not much experienced with Swing but I can't get it work. Does anybody tried it in jdk 1.6.0_16?

@ATorras I know you asked this a while back but if any other newbies had my issues, remember to picLabel.setBounds();

you answered it 2 years after it was asked and got more upvotes than the accepted answer. congrats, and nice code

java - How to add an image to a JPanel? - Stack Overflow

java image swing jpanel
Rectangle 27 482

If you are using JPanels, then are probably working with Swing. Try this:

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);

The image is now a swing component. It becomes subject to layout conditions like any other component.

how to scale the image according to the size of the JLabel?

Nice code! I'm not much experienced with Swing but I can't get it work. Does anybody tried it in jdk 1.6.0_16?

@ATorras I know you asked this a while back but if any other newbies had my issues, remember to picLabel.setBounds();

you answered it 2 years after it was asked and got more upvotes than the accepted answer. congrats, and nice code

java - How to add an image to a JPanel? - Stack Overflow

java image swing jpanel
Rectangle 27 482

If you are using JPanels, then are probably working with Swing. Try this:

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
add(picLabel);

The image is now a swing component. It becomes subject to layout conditions like any other component.

how to scale the image according to the size of the JLabel?

Nice code! I'm not much experienced with Swing but I can't get it work. Does anybody tried it in jdk 1.6.0_16?

@ATorras I know you asked this a while back but if any other newbies had my issues, remember to picLabel.setBounds();

you answered it 2 years after it was asked and got more upvotes than the accepted answer. congrats, and nice code

java - How to add an image to a JPanel? - Stack Overflow

java image swing jpanel