I am making a program where the user chooses an image file on their computer and it displays it in a window. I have the line of code
image = ImageIO.read(getClass().getResourceAsStream(path));
where path is the absolute path to the image. The error it returns is
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
What am I doing wrong or is it not possible to get an Image outside of the project file?
So, getClass().getResourceAsStream() reads the image from default class path(either in the folder of your classes or the contents of the jar file)!
So you would want :
BufferedImage img = null;
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
}
Related
I would like to load an image from my current src directory where the java class files are located as well. However, I always get an IOException..
And how can I make sure the file gets loaded properly on Mac/Linux as well on Windows?
My code so far:
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
IOException message:
Can't read input file!
(My path is correct - is it because of the space between Google and Drive?)
/Users/myMac/Google Drive/Privat/Programming/Logo_transparent.png
Kind regards and thank you!
I think It's because you didn't create the file, You can create the file if it doesn't exist by using this code
if(!imageFile.exists()) imageFile.createNewFile();
You're code will look like this
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
if(!imageFile.exists()) imageFile.createNewFile();
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
Also you shouldn't concat child files like that instead pass it as a second argument.
File imageFile = new File(System.getProperty("user.dir"), "Logo_transparent.png");
If your image files will be packaged together with your class files (for example in the same .jar) you should not use File but read it as a resource:
bufferedImage = ImageIO.read(this.getClass().getResourceAsStream("/Logo_transparent.png"));
Notice the '/' before the file name. This means to search in the root path of the classpath.
If you specify without / it will search in the package of this (the current class)
this.getClass().getResourceAsStream("Logo_transparent.png")
You can try to build the absolute path to the image like here and read it afterward.
I am making a game in java which involves drawing images to a frame. When I attempt to draw the images, I get the following error:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1348)
at main.Game.<init>(Game.java:57)
at main.Game.main(Game.java:319)
Why am I getting this? Here is the code for the area I am accessing the files:
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("resources/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("resources/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("resources/enemy.png"));
highScoreReader = new BufferedReader(new FileReader("/files/HIGH_SCORE.txt"));
highScoreWriter = new BufferedWriter(new FileWriter("/files/HIGH_SCORE.txt"));
} catch (Exception e) {
e.printStackTrace();
}
Here is a picture of the file directories:
Am I coding the directory wrong? Am I not grabbing the image correctly?
Is the "s", you have "resour'C'es" and the folder is "resour'S'es"
Your resource folder is named resourses but your code is calling from "resources/player.png".
I have created code that makes print screens and saves them as an imiage, but I don't really know how to change the path of saving the file for other folder in my main project folder. Any ideas?
private static void print(JPanel comp, String nazwa) {
// Create a `BufferedImage` and create the its `Graphics`
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(comp.getWidth(), comp.getHeight());
Graphics graphics = image.createGraphics();
// Print to BufferedImage
comp.paint(graphics);
graphics.dispose();
// Output the `BufferedImage` via `ImageIO`
try {
ImageIO.write(image, "png", new File(nazwa+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
Write the full path in the File constructor:
new File("/home/cipek/images/filename.png")
However I have still got a problem. I am not sure that udnerstand it properly.
cipek- is my project name
images- folder where i want to keep images
But what about home?? I rewrite "home" however it doesn't work.I don't want to give whole path because I will use this proram on other computers so the path will be diffrent every time.
I'm using a simple way to get my resources for the project. I'm using Eclipse, and I have a 'res' folder to hold the needed files. This is how I load stuff, for example a 'puppy.png' just in my res folder (no subfolders):
String path = "/puppy.png";
try {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
} catch(Exception ex) { ex.printStackTrace(); }
And sometimes I get an input==null error, and sometiomes not! Not like this time puppy.png loaded but next time it won't. For some classes it always loads correctly, and for the other classes I always get this error. Can anyone explain why can this happen, and how can I fix it, but still use the getResourceAsStream() method?
Please have a look at How to retrieve image from project folder?.
I have mentioned no of ways to read image from different paths.
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
In your case the image must be in the same package where is the class and don't prefix /.
Note that if the resource returns null (meaning it doesn't exist), you will get this error.
Check the input returned like so:
String path = "/puppy.png";
try {
InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
//resource doesn't exist
} else {
BufferedImage image = ImageIO.read(is);
}
} catch(Exception ex) { ex.printStackTrace(); }
Note that you most likely should be using String path = "puppy.png", seeing as you will already be in the content of the project folder.
This question already has answers here:
Get resource from jar
(4 answers)
Closed 9 years ago.
I have tried searching and still haven't got the solution. When I export to a jar file all my images suddenly do not work anymore. They run fine out of eclipse and I have made sure that they are in the jar file. I have tried using get resource methods and making a image-loader class to automatically go up the directory tree but it still fails. Here is what I have done:
public static Image load(String path)
{ String temp = path;
Image image = null;
try {
image = new ImageIcon(path).getImage();
}
catch ( Exception e )
{
try {
while (image == null )
{
image = new ImageIcon("../"+ path).getImage();
}
if ( path.equals("../../../../../../"+ temp))
{
while ( image ==null)
{
image = new ImageIcon("./"+ path).getImage();
}
}
}
catch ( Exception ae)
{
System.err.println("cannot locate image");
}}
return image;
}
the path I will send it look as follows: "doc/icon.png"
I have placed all my images in the doc folder, the structure is final Project, inside there is doc folder and then the src folder that contains all the packages.
Try using this:
Image.class.getClassLoader().getResource("/filepath/filename").getFile()
Instead of "Brute-force" the image path try to figure out what's the path you try to load the image from. You can look it up with the following
System.out.println("Path: " + (this.getClass().getClassLoader().getResource("")).getPath());
afterwards try to load it like this or like #Balint Bako allready sed.
Image img;
URL url = new File("the path you found out").toURI().toURL();
BufferedImage img = ImageIO.read(url);