Loads an image without having to worry about exceptions. - Java 2D Graphics

Java examples for 2D Graphics:Image Load

Description

Loads an image without having to worry about exceptions.

Demo Code


//package com.java2s;
import java.awt.image.*;
import javax.imageio.*;
import java.net.*;

public class Main {
    /**/*from w w  w  .  ja  va  2s.  co m*/
     * Loads an image without having to worry about exceptions.
     * If the image won't load, a blank one is created.
     * @param path image path
     * @param expectedWidth width to make the blank image, if necessary.
     * @param expectedHeight height to make the blank image, if necessary.
     * @return the image
     */
    public static BufferedImage loadImage(String path, int expectedWidth,
            int expectedHeight) {
        BufferedImage image = null;
        try {
            URL url = translateURL(path);
            image = ImageIO.read(url);
        } catch (Exception ex) {
            image = new BufferedImage(expectedWidth, expectedHeight,
                    BufferedImage.TYPE_INT_ARGB);
        }
        return image;
    }

    /**
     * Determines whether a path is absolute or relative and translates it to a URL accordingly.
     */
    public static URL translateURL(String path) {
        URL result = null;
        try {
            //Still needs a bit of tweaking to make it work on Windows
            if ("/".equals(path.substring(0, 1))) {
                result = new URL("file:" + path);
            } else {
                //This works in or out of jar files
                result = Thread.currentThread().getContextClassLoader()
                        .getResource(path);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}

Related Tutorials