Java Graphics How to - Convert to PNG format image and show on dialog








Question

We would like to know how to convert to PNG format image and show on dialog.

Answer

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
/* w w w  . ja  v  a  2s.  co m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;

public class Main {

  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    BufferedImage origImg = ImageIO.read(url);

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(origImg)));

    File newFile = new File("new.png");
    ImageIO.write(origImg, "png", newFile);
    BufferedImage newImg = ImageIO.read(newFile);

    JOptionPane.showMessageDialog(null, new JLabel("New",
        new ImageIcon(newImg), SwingConstants.LEFT));
  }
}