-2

I want to read a bunch of image files from my current package because I want to get access to the files when my package which includes my image files is exported to others' computer.

I just want to make sure my program can read the images no matter if the package is in my computer.

I tried

  File file = new File("images.jpg"); // It is wrong because the path is wrong.
  // I want to assign the image as BuffuredImage      
  BufferedImage dealerCardImage1 = ImageIO.read(file); 

I was wondering how the path of the files should be. What should I do?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

3 Answers3

1

put your image file inside the package of current class file and try this:

BufferedImage dealerCardImage1 = ImageIO.read(getClass().getResourceAsStream("images.jpg"));

Note that, getClass().getResourceAsStream(path) returns an InputStream that points to a path that starts from current package.

For example if you have a class file named HelloWorld inside package com.example, then HelloWorld.class.getResourceAsStream("images.jpg") returns an InputStream to image with this path: com/example/images.jpg

S.Yavari
  • 876
  • 8
  • 25
0

if you read from file use

    Image image = new Image();

            image = ImageIO.read(file);

            // Read from an input stream
            InputStream is = getClass()
.getResourceAsStream("/com/statement/SamplePDFStatementFile.txt");
            image = ImageIO.read(is);

//if you read from url

// Read from a URL
    URL url = new URL("http://hostname.com/image.gif");
    image = ImageIO.read(url);
Nambi
  • 11,944
  • 3
  • 37
  • 49
-1
ImageIO.read(file); will return null if no registered ImageReader is not found. 

Please check whether you have registered any ImageReader or not.

I think this code snippet could help you

File file = new File("images.jpg"); // Assuming images.jpg in my working directory  
FileInputStream fis = new FileInputStream(file);  
BufferedImage image = ImageIO.read(fis); //reading the image file 

You just need to wrap the file into an FileInputStream and then pass it to read()

Sasi Kathimanda
  • 1,788
  • 3
  • 25
  • 47
  • It's a jpg -- why would there not be an image reader for it? And why suggest he read the image as a File when it is in fact a resource? – Hovercraft Full Of Eels Dec 15 '13 at 04:28
  • OP mentioned about NPE - so i am trying to say the causes that might lead to it. OP also want to read a FILE to BI , so i just thought of having other simpler alternatives rather using streams. – Sasi Kathimanda Dec 15 '13 at 04:56