Saturday, April 28, 2012

How to read an image from a File, InputStream, or URL


This post shows you how to read an image from a File, InputStream, or URL based in ImageIO API:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GetDisplayImage extends Panel {

    private static Image image = null;
    private static int w, h;

    public GetDisplayImage(int type, String path) {

        try {
            switch (type) {
                case 1:
                    // Read from a file
                    File file = new File(path);
                    image = ImageIO.read(file);
                case 2:
                    // Read from an input stream
                    InputStream is = new BufferedInputStream(
                            new FileInputStream(path));
                    image = ImageIO.read(is);

                case 3:
                    // Read from a URL
                    URL url = new URL(path);
                    image = ImageIO.read(url);
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }

    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rafa Pictures");
        Panel panel = new GetDisplayImage(1, "D:/rafa/nadal.jpg");
        
        //Panel panel = new GetDisplayImage(3, "https://lh3.googleusercontent.com  
        /_rmcLs25xGaM/TVzVw_uPD9I/AAAAAAAAAJg/oxia1Y0SFdo/s512/rafa_gt.png");

        frame.getContentPane().add(panel);
        w = image.getWidth(panel);
        h = image.getHeight(panel);
        frame.setSize(w, h);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

No comments:

Post a Comment