load Buffered Image From Classpath - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

load Buffered Image From Classpath

Demo Code


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Main{
    public static void main(String[] argv) throws Exception{
        String resourceName = "java2s.com";
        int type = 2;
        System.out.println(loadBufferedImageFromClasspath(resourceName,type));
    }//from   ww w.j  a  v a2s .  c  o m
    public static BufferedImage loadBufferedImageFromClasspath(
            String resourceName, int type) {
        final BufferedImage image;
        try {
            URL url = BufferedImageUtils.class.getClassLoader()
                    .getResource(resourceName);
            if (url == null) {
                throw new RuntimeException("Resource not found: "
                        + resourceName);
            }
            image = ImageIO.read(url);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load: " + resourceName);
        }

        return getBufferedImageAsType(type, image, image.getWidth(),
                image.getHeight());
    }
    private static BufferedImage getBufferedImageAsType(int type,
            BufferedImage image, int sizeX, int sizeY) {
        if (image.getType() == type) {
            return image;
        } else {
            // 'type' should be one of BufferedImage.TYPE_*
            BufferedImage result = new BufferedImage(sizeX, sizeY, type);
            Graphics g = result.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();

            return result;
        }
    }
}

Related Tutorials