Avoid full file paths when importing files - java

Trying to read an image into java, currently what I have to do is this:
Image img = new Image("file:E:/Javaworkspace/Project/src/resource/image.png");
However, I am not the only one going to be working on that project and this path works only in my machine. I did try
Image img = new Image("file:/resource/image.png")
but this leads to FileNotFound. I don't know what this thing is called in English, I hope you understand what I am trying to convey here.
EDIT:
I added the folder "resource" via Build Path now and am trying to get input stream as such:
ImageView imgView = new ImageView(new Image(this.getClass().getResourceAsStream("/resource/image.png")));
Needless to say, I get a NullPointerException, which according to the documentation, occurs when the path doesn't exist. How can it not exist after I specifically created it via Build Path, it exists in CLASSPATH. (Yes, the file is there too or can I not simply copy it into the folder? )

Place the image inside the project folder rather than using file system to access the file. Then you can use this:
Image image = ImageIO.read(getClass().getResourceAsStream("/resource/image.png"));
to get the image file where ever required by anyone.

I believe you can always try user.home but then if one person updates an image or adds one it won't update for you.
Image img = this.getClass().getResource("/resource/image.png");
Probably messed up parentheses
Also make sure you have folder "resource" in right folder (most likely same folder src and out are in

Related

Cannot Construct An Image Object With Relative File Path WIthout Using file: Prefix

I have been trying to create an image object like this:
Image img = new Image("images/jack.png");
or
Image img = new Image("jack.png");
or /jack.png or /images/jack.pngetc.
I have looked up the working directory using System.getProperty("user.dir") and it is indeed where I put my image file. When I use file: prefix, it does work, like so:
Image img = new Image("file:images/jack.png");
However, it is also supposed to work without using it. In the textbook it is done without file:. I've seen other codes that work without it.
At the end of a bunch of chained exceptions, it says:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
I also tried to read source code from OpenJDK and I could figure anything out because many methods were native and from what I traced I didn't understand how it didn't work. Also, I can create files the same way, I just can't create images. For instance, this works:
File file = new File("fileName.txt");
What causes this problem, what should I do to fix it?
I'm using NetBeans, if that matters.
Note that System.getProperty("user.dir") does not return the working directory. It returns the user directory.
A path relative to the working directory can be specified using a relative file path in the File constructor. However it's bad practice to rely on the working directory. Starting the application from NetBeans results in the working directory being the project directory, but this is not the case, If started in a different way.
Images you need in your application should therefore be added to the jar.
In this case you can retrieve the image URL via Class.getResource(). (convert to String using toExternalForm().)
If you have a File that references a image file, you can use the File instance to get a URL:
File file = ...
String urlString = file.toURI().toURL().toExternalForm();
Those URLs can be used with the Image constructor.
Note that
File file = new File("fileName.txt");
does not create a file. It just represents a file path. This file may or may not exist. Simply invoking the File constructor does not create a new one.
File file = new File("name.txt");
creates a file somewhere. It doesn't read the existing file whereas
Image image = new Image("pathToImage.png");
tries to read the existing image. In order to be able to read an image stored somewhere you need either the absolute path, which requires the protocol (http, file, ftp etc.) or you put your image into the 'known' directory, like the resources dir of your project.
Say, you have your java sources under src/main/java. The resources dir could be src/main/resources. Put your image there and try working with relative path relative to src/main/resources.

when I use getInstance of itext for image it is redirecting to different location [duplicate]

I'm doing the letter generation with iText (pdf/rtf) in java servlet and got a problem with accessing images. The images are in the WebContent/images folder. When I run it in a local server and pointing the full path of images directory (c://eclipse/myproject/WebContent/images/letterHead.jpg) its working, but it fails running on the server with the directory ("WebContent/images/letterHead.jpg").
The project is being deployed as a WAR on a tomcat server, thus ending up with an address similar to
http://someserver:8081/projectName/someJSP.jsp
I don't understand how to reference the images relatively in this environment, and any help would be much appreciated.
Here is my code
Image imghead = Image.getInstance("WebContent/images/letterHead.jpg");
imghead.setAbsolutePosition(35,770);
imghead.scaleAbsolute(125, 42);
document.add(imghead);
You should never use relative paths in java.io stuff. You will be dependent on the current working directory which is in no way controllable in case of a webapplication. Always use absolute disk file system paths. Thus, c:/full/path/to/file.ext.
You can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path. The relative web path is rooted on the public webcontent folder which is in your case thus /WebContent. So, you need to replace the first line of above code by:
String relativeWebPath = "/images/letterHead.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image imghead = Image.getInstance(absoluteDiskPath);
// ...
Following piece of code may help you...
String path = request.getContextPath();
String split_path[] = path.split("/");
path = request.getRealPath(split_path[0]);
String imagePath="\\resources\\images\\letterHead.jpg";
Image image = Image.getInstance(path+imagePath);
Following code can be used to access image path inside a java class.
URL imageUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
Image img=Image.getInstance(imageurl+"../../../some/images/pic.gif");
So I had the same problem, I wanted to add an image to the pdf but through a relative path, so when I made a executable program it would work in any computer, even if it had or not the image saved.
I found a way where you add the image as a resource of your application. You need to put the image inside the src directory or the dir of the class where you call it and then you can use the following code:
Image image = Image.getInstance(yourClassName.class.getResource("/yourImageName")));
If you put the image inside a folder then, obviously, you'll need to add the path through the folders name ("folderName/yourImageName"). Hope it helps!
For Kotlin, if the image is in the resources folder, you can also try the following:
Image.getInstance(this::class.java.classLoader.getResourceAsStream("images/your_image.png").readBytes())
Resources
Image foto = Image.getInstance(this.getClass().getResource("/static/img/gobierno.jpg"));

Finding a resource in Java

I am developing a Java application which displays a big amount of images. The problem is I can't figure out how to make Java find these images.
I have followed several tutorials and answers here at Stackoverflow, but I still haven't managed to find a solution that works regardless of OS (Linux or Windows) and running method (embedded on eclipse or exported jar file). This might be due to the fact that I am still a newbie, though.
I have created a class, which I call myIcon and through this class I mean to access all of these images. In the following code, I want to pass the string "resources/icon/image.gif" to the function getIconPath. The output should be a ImageIcon of this image, since this file exists. Despite that, if I pass to this function the path to an image that doesn't exist, null should be returned. In this case, my application will display a default image (a red x).
public class MyIcon {
// some other functions and properties
private static final ImageIcon getIconPath(String path) {
File f = new File(path);
if (f.exists()) {
return new ImageIcon(path, "");
} else {
return null;
}
}
}
The resources folder is a sibling to the src folder in my directory structure. That is, both resources and src are subfolders of the root directory.
When I run the code above, no image is ever found. The default image is thus always displayed and getIconPath returns null.
I am also aware of the getResource method of ClassLoader, but I still don't really understand how these things should be used.
While running in eclipse, you should print out f.getAbsolutePath(). It probably doesn't point to your file. More generally, you want to access the file as a resource. See:
https://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html
There are two parts to this - making sure that when you build a jar, the images are part of it, and accessing a resource within the jar.
For the first part, I am guessing that whatever you're using to build a jar, it will put your images into the META-INF folder, which should work without too much issue (if its not there, or in with the Java class/source in the generated jar, that might cause the lookup to fail)
There is another Stack Overflow Post for the second part. The key is to make sure the images you want to load are on the classpath.
Hope this helps!
If resources is in classpath, you can find for the image at classpath, using getResource(String name) or getResourceAsStream(String name).
However, in a simple Java Project, even adding resources to build path, like this:
it will just put the folder content, in other words, just icon/..., to bin folder, something like this:
So, since resources isn't in classpath, just icon, to retrieve the images, you'll need to inform as path only /icon/image.gif, like this:
URL url = YourClass.class.getResource("/icon/image.gif");
ImageIcon icon = new ImageIcon(url);

getting resource as stream returns InputStream must not be null

I'm trying to get an image in this way:
Node rootIcon = new ImageView(new Image(this.getClass().getResourceAsStream("folder.png")));
I guess that I need to place the image in another folder or to set the path to it in other way. The image is in src\main\resources\icon and the class itself is in src\main\java\package\package\package\class
how to find out what path I need to set or where shall I put the image to?
Try .getResourceAsStream("/icon/folder.png"). If you use maven then, the content of src/main/resouces is automatically added to your jar file. Eclipse for example adds that folder to the calls path, if it is a source folder. So running from Eclipse should work too.

Opening image asset Java JDK 8

I am attempting to load an image called Default.png stored within the project and draw it onto a canvas. I am well aware of ImageIO.read however no matter what path I give it, I can't seem to load it. Where should I put the image? I have tried putting it in a separate folder calles "res," putting it into assets.author.mypackagename.textures, but no matter what I do I cannot seem to find the right location and how to access it. Any help is appreciated, comment for further specifics.
Actually the resources are loaded in the classpath relative to the current package. If /com/daniel/project/src/ is in your classpath, and images are in /com/daniel/project/src/image then use:
ImageIO.read( ClassLoader.getSystemResource( "image/Default.png" ) );
But the src folder is not included in the classpath by IDEs generally. Try adding the image to the bin folder.
If You have it in a separate folder called res you can load the image by doing this:
ImageIO.read(this.getClass().getResource("/Default.png"));
you can also do something like:
ImageIO.read(new File("res/Default.png"));
The second method doesn't need the picture to be in another folder, but for me it's cleaner that way.

Categories

Resources