Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image from a filepath via BufferedImage

I have a problem with Java application, particular in loading a image from a location in my computer.

Following this post I used a BufferedImage and a InputFileStream to load an image on my computer. First, I put the image (pic2.jpg) into the source code and that is working. However, if I put the image to another place (let's say C:\\ImageTest\pic2.jpg), Java IDE show me an IllegalArgumentException

return ImageIO.read(in);

here is the code:

public class MiddlePanel extends JPanel {
    private BufferedImage img;

    public MiddlePanel(int width) {    
        //img = getImage("pic2.jpg");       
        img = getImage("C:\\ImageTest\\pic2.jpg");

        this.setPreferredSize(new Dimension(800,460));

    }

    public void paintComponent(Graphics g) {
        // ...
    }

    private BufferedImage getImage(String filename) {
        // This time, you can use an InputStream to load
        try {
            // Grab the InputStream for the image.                    
            InputStream in = getClass().getResourceAsStream(filename);

            // Then read it.
            return ImageIO.read(in);
        } catch (IOException e) {
            System.out.println("The image was not loaded.");
            //System.exit(1);
        }

        return null;
    }
}
like image 622
Lup Avatar asked Oct 18 '13 10:10

Lup


People also ask

What is the difference between BufferedImage and image?

List, the difference between Image and BufferedImage is the same as the difference between List and LinkedList. Image is a generic concept and BufferedImage is the concrete implementation of the generic concept; kind of like BMW is a make of a Car. Show activity on this post. Image is an abstract class.

Can ImageIO read PNG?

imageio package. Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can "plug-in" support for additional formats.

Which method is used for load the image?

Answer: getImage(URL object, filename) is used for this purpose.


1 Answers

To read an .jpg file from non-relative path you could use this:

BufferedImage img = null;

try 
{
    img = ImageIO.read(new File("C:/ImageTest/pic2.jpg")); // eventually C:\\ImageTest\\pic2.jpg
} 
catch (IOException e) 
{
    e.printStackTrace();
}

I do not have any Java environment at the moment, so hope it works and is written correctly.

like image 91
Tafari Avatar answered Oct 03 '22 23:10

Tafari