Saturday 11 January 2020

Open, Read, Display image File using Java Program | Java Slide Making

Open, Read, Display image File using Java Program | Java Slide Making

Java program to show an image in a JFrame


Here you find the Java Swing source code for a program that does all those things, eventually displaying the image you provide in a JFrame:

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * A Java class to demonstrate how to load an image from disk with the
 * ImageIO class. Also shows how to display the image by creating an
 * ImageIcon, placing that icon an a JLabel, and placing that label on
 * a JFrame.
 *
 * @author alvin alexander, alvinalexander.com
 */
public class ImageDemo
{
  public static void main(String[] args) throws Exception
  {
    new ImageDemo(args[0]);
  }

  public ImageDemo(final String filename) throws Exception
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        JFrame editorFrame = new JFrame("Image Demo");
        editorFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
       
        BufferedImage image = null;
        try
        {
          image = ImageIO.read(new File(filename));
        }
        catch (Exception e)
        {
          e.printStackTrace();
          System.exit(1);
        }
        ImageIcon imageIcon = new ImageIcon(image);
        JLabel jLabel = new JLabel();
        jLabel.setIcon(imageIcon);
        editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);

        editorFrame.pack();
        editorFrame.setLocationRelativeTo(null);
        editorFrame.setVisible(true);
      }
    });
  }
}

compiling this program


 ImageDemo.java

To run the program


java ImageDemo path-to-your-image



Open, Read, Display image File using Java Program | Java Slide MakingOpen, Read, Display image File using Java Program | Java Slide MakingOpen, Read, Display image File using Java Program | Java Slide MakingOpen, Read, Display image File using Java Program | Java Slide Making

No comments:

Post a Comment