load Buffered Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

load Buffered Image

Demo Code


//package com.java2s;
import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String fileName = "java2s.com";
        int type = 2;
        System.out.println(loadBufferedImageAsType(fileName, type));
    }/*from   w  ww .j a  va  2s  . c o  m*/

    public static BufferedImage loadBufferedImageAsType(String fileName,
            int type) {
        final BufferedImage image;
        try {
            image = ImageIO.read(new File(fileName));
        } catch (IOException e) {
            throw new RuntimeException("Could not load image: " + fileName,
                    e);
        }

        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