Sep 15, 2012

How To Load And Display Image From File In Java

Java IO
In this Java tutorial, we set to graphically display image from a directory. We first set a file reference to our image directory, in this case we gonna use BufferedImage object to get the decoded buffered image, automatically invoking ImageReader. You can see no ImageInputStream is physically used, this is because the file is wraped in an image input stream as soon as it register the file to the ImageReader object. Null is returned if the registration failed.
package codecypherprojects;

/**
 *
 * @author Khamis
 */

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;


public class LoadAnshowImageFromFile extends JPanel {
          
    BufferedImage image;
    private static JPanel imagePanel;
    private static JFrame frame;
    //You can specify your own image directory
    private String dir = "c:/FileFolder/codecypher.jpg";


    public LoadAnshowImageFromFile() {
       try {
          /**
           * ImageIO.read() returns a BufferedImage object, decoding the supplied  
           * file with an ImageReader, chosen automatically from registered files 
           * The File is wrapped in an ImageInputStream object, so we don't need
           * one. Null is returned, If no registered ImageReader claims to be able
           * to read the resulting stream.
           */
           image = ImageIO.read(new File(dir));
       } catch (IOException e) {
           //Let us know what happened
           System.out.println("Error reading dir: " + e.getMessage());
       }

    }
    //We set our preferred size if we succeeded in loading image
    public Dimension getPreferredSize() {
        if (image == null) {
             return new Dimension(100,100);
        } else {
           return new Dimension(image.getWidth(null), image.getHeight(null));
       }
    }
    
    //Draw our image on the screen with Graphic's "drawImage()" method
    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    public static void main(String[] args) {

        frame = new JFrame("Loading Image From File Example");  
        imagePanel = new JPanel();
        //Release the resource window handle as we close the frame
        frame.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        imagePanel.add(new LoadAnshowImageFromFile());
        frame.add(imagePanel);
        frame.pack();
        frame.setVisible(true);
    }
}
Here is the result of the program.

















Related Posts 


Auto-Scroll Texts with Image Background in Java

How To Make a Copy of File in Java

7 comments:

  1. This is good work!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I'm learning from the code here, but I have some suggestions:

    1. Java is really good at doing cross-platform development. It would be best if pathnames in code didn't assume that Windows is the OS.

    private String dir = "c:/FileFolder/codecypher.jpg";

    The above full path name only works in Windows. It won't work in Mac, Android, Unix. Windows does have a lion's share of the market, but it's best to use code that works for all platforms.

    Also, this could be called something like "fullPath" -- not "dir". It doesn't specify a directory, it specifies a file.

    I have more ideas for improvements, but this is enough for now.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete