Loads an image from file at the input path and returns it as an ImageIcon - Java 2D Graphics

Java examples for 2D Graphics:Image File

Description

Loads an image from file at the input path and returns it as an ImageIcon

Demo Code


//package com.java2s;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
    public static void main(String[] argv) throws Exception {
        String path = "java2s.com";
        System.out.println(loadImage(path));
    }/*from  w  ww  . j  a v  a2  s  .co m*/

    /** Loads an image from file at the input path and returns it as an ImageIcon 
     * 
     * @param path The path to the image file
     * @return The image icon loaded or null if the file doesn't exist or couldn't
     *         be loaded
     */
    public static ImageIcon loadImage(String path) {
        // First ensure the file exists
        File imageFile = new File(path);

        if (imageFile.exists()) {
            // Load, scale and return the button
            try {
                Image image = ImageIO.read(imageFile);
                return new ImageIcon(image.getScaledInstance(20, 20, 0));
            }

            catch (IOException ignore) {
            }
        }

        return null;
    }
}

Related Tutorials