Java BufferedImage Load loadFromResource(String imageName, Class cls)

Here you can find the source of loadFromResource(String imageName, Class cls)

Description

Loads an Image named imageName as a resource relative to the Class cls.

License

Open Source License

Declaration

public static Image loadFromResource(String imageName, Class cls) 

Method Source Code

//package com.java2s;
/**//from  www.  ja  v  a2s  .  com
 * $RCSfile$
 * $Revision: 128 $
 * $Date: 2004-10-25 20:42:00 -0300 (Mon, 25 Oct 2004) $
 *
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.*;

import java.net.URL;
import java.util.Hashtable;

public class Main {
    private static Hashtable imageCache = new Hashtable();

    /**
     * Loads an {@link Image} named <code>imageName</code> as a resource
     * relative to the Class <code>cls</code>.  If the <code>Image</code> can
     * not be loaded, then <code>null</code> is returned.  Images loaded here
     * will be added to an internal cache based upon the full {@link URL} to
     * their location.
     * <p/>
     * <em>This method replaces legacy code from JDeveloper 3.x and earlier.</em>
     *
     * @see Class#getResource(String)
     * @see Toolkit#createImage(URL)
     */
    public static Image loadFromResource(String imageName, Class cls) {
        try {
            final URL url = cls.getResource(imageName);

            if (url == null) {
                return null;
            }

            Image image = (Image) imageCache.get(url.toString());

            if (image == null) {
                image = Toolkit.getDefaultToolkit().createImage(url);
                imageCache.put(url.toString(), image);
            }

            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. loadFromURL(String url)
  2. loadImage(byte[] data)
  3. loadImage(ClassLoader classLoader, String path)
  4. loadImage(File file)