Java ImageIcon Load loadImageIcon(String imageName)

Here you can find the source of loadImageIcon(String imageName)

Description

Loads an image from a given path and returns it as an ImageIcon.

License

LGPL

Parameter

Parameter Description
imageName path to image

Exception

Parameter Description
IllegalArgumentException when image can't be found in classpath

Return

loaded image

Declaration

public static ImageIcon loadImageIcon(String imageName) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.awt.Image;

import java.awt.Toolkit;

import java.net.URL;
import javax.swing.ImageIcon;

public class Main {
    private static final String IMAGE_PATH = "images/";

    /**//from   w  w  w  .j a  va 2s  .c om
     * Loads an image from a given path and returns it as an ImageIcon.
     * 
     * @param imageName path to image
     * @return loaded image
     * @throws IllegalArgumentException when image can't be found in classpath
     */
    public static ImageIcon loadImageIcon(String imageName) {
        return new ImageIcon(loadImage(imageName));
    }

    /**
     * Loads an image from the given path.
     * 
     * @param imageName path to image
     * @return loaded image
     * @throws IllegalArgumentException when image can't be found in classpath
     */
    public static Image loadImage(String imageName) {
        URL imageUrl = Thread.currentThread().getContextClassLoader().getResource(IMAGE_PATH + imageName);
        if (imageUrl == null) {
            throw new IllegalArgumentException("'" + imageName + "' could not be found in classpath");
        }

        return Toolkit.getDefaultToolkit().getImage(imageUrl);
    }
}

Related

  1. getImageIcon(URL u, int w)
  2. getImageIcon(URL url)
  3. getScaledInstance(Image img, int targetWidth, int targetHeight)
  4. loadImageIcon(byte bytes[], String descr)
  5. loadImageIcon(Class clas, String iconPath)
  6. loadImageIcon(String url)
  7. loadResourceImageIcon(String imageName)
  8. readImageIconFromFile(File srcFile)