JavaFX image pathway issues - java

I have just figured out how to unzipped a zippedfolder into the folder EBookReader/books from within my program (where EBookReader is my project). Now I have a /books/testbook/1.png (what was unzipped) however no matter what I do I can not get the program to display an image on that pathway.
System.out.println(loadedBook.returnPage());
Image page = new Image(getClass().getResourceAsStream(loadedBook.returnPage()));
ImageView imagePage = new ImageView();
imagePage.setImage(page);
imagePage.setFitWidth(350);
imagePage.setFitHeight(500);
imagePage.setPreserveRatio(true);
imagePage.setSmooth(true);
imagePage.setCache(true);
border.setCenter(imagePage);
loadedBook.returnPage() returns the string "F:\EbookReader\books\testBook\1.png" which just so happens to be the location of the image 1.png and even if I enter the string manually into the image location it still doesn't work. I heard I didn't need the getClass() junk but it doesn't work without that either. The only way I have gotten it to work is if I put the image in directly in F:\EbookReader\src\ebookreader.
EDIT: The error is that the input stream is null!

getResourceAsStream() is expecting a location either relative to the current class, or relative to the classpath. The path you showed certainly is not relative to either of those.
I recommend using the Imageconstructor taking a URL and doing
Image page = new Image(new File(loadedBook.returnPage()).toURI().toString());
You could also do
Image page = new Image(new FileInputStream(new File(loadedBook.returnPage())));

Related

Path location of the image cannot locate in Eclipse swt

I have a problem when exporting my java project. It cannot find the path of my image.
File Project
src
config
image
copy.png
This is where my image is located
String image1 = "image/copy.png";
shell.setImage(new Image(display, image1));
It works before i export but when i export it and update my program it gives me an error. I tried also to use InputStream but it gives me null.
With the specified class, org.eclipse.swt.graphics.Image, you will want to create the Image with method Image(Device device, InputStream stream) and use getClass().getResourceAsStream( image1 ) to supply the inputStream containing the file. You probably need "/" at the start of your path.
Create image with this method work well.
new Image(device, getClass().getResourceAsStream(localImagePath));

Create image from local relative path in java

I have an application in netbeans with a folder in the same directory as the application containing all the images, and I also have an attribute String in the class where I save the absolute path when I upload an image.
How can I obtain the relative path of an image inside the same jar to store it in a string?
Because then I create the image from the URL string.
Edit:
I have a jar including a logic package, a presentation package (with swing) and an image package. In the logic I've tried to do:
String img = new String("\src\Images\Image.jpg"):
ImageIcon icon = new ImageIcon(img);
Icon imagen = new ImageIcon(icon.getImage().getScaledInstance(photo.getWidth(),photo.getHeight(),Image.SCALE_DEFAULT));
photo.setIcon(imagen);
Recommendations:
Never create a new String with the new String(...) constructor. There's no need to do this, and you just waste resources unnecessarily. Instead simply use a String literal.
Don't use Files to get images held inside of Jar files. Jar files do not hold Files.
By passing a String into your ImageIcon's constructor, you're doing just that (check the API), you're trying to get the image as a File.
Instead use ImageIO.read(...) and a resource to get the image.
The resource path will all depend on your Jars structure, something you have yet to show us.
e.g.,
String path = "\Images\Image.jpg"; // this path may not be correct
InputStream imgStream = getClass().getResourceAsStream(path);
BufferedImage img = ImageIO.read(imgStream);
// process your image here if desired
ImageIcon icon = new ImageIcon(img);

Java swing Image always has height and width of -1

I know that the method returns -1 when it couldn't get the width or height of the image, but I hope you can tell me why it can't manage to do that. Here I create a few ImageIcons and save them in an Image Array:
for(int x = 0; x < playerSprites.length; x++){
playerSprites [x] = new ImageIcon("player" + x + ".png").getImage()
}
Later I create an instance of the class which only creates this Array at the moment. When I then want to get the images from the Array in the other class I check their height and width and I always get -1 on both:
public Image nextImage(String name){
Image image = null;
if(name.equals("player")){
if(counter == animationImageManager.getPlayerSprites().length-1){
counter = 0;
}
image = animationImageManager.getPlayerSprites()[counter];
counter++;
}
return image;
}
If image is not found then still it return -1 for height and width.
Try below sample code to reproduce the issue:
System.out.println(new ImageIcon("").getImage().getWidth(null)); // print -1
It's worth reading Java Tutorial on Loading Images Using getResource
May be it's not loading the images properly.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
Read more...
The width/height for Image will return -1 if the image is null. When there's no image.
Suggestions:
use ImageIO.read() which will throw an IOException if something goes wrong with the IO, like the path being wrong.
If the image is a resource for your application, then don't read it as a file, read it as a resource via URL. For instance, if the image is in src/images, then you could do
URL url = getClass().getResource("/images/myimage/png");
BufferedImage image = ImageIO.read(url);
Important thing to note with ImageIcon is when you pass a String to the constructor, it will look for the file in the local file system. It may work when you are developing, but once you deploy the application with the images in the jar, it won't work anymore, with the file path, because it will no longer be valid. You could pass the URL to ImageIcon just the same as above, but like I said, ImageIO allows for more error detection.
Just so you understand what's going on in your current code, by you specifying just the image file name as the path to the ImageIcon, the search will look for the image in the root of the project folder (if you're working in an IDE) because that's the working directory. So if your images aren't there, the images won't be found.
Another thing to note about my second bullet point is how the image is search for. You can see the path I used "/images/myimage/png". What the / in the front does, is bring the search to root of the classpath, which in development view, is the src. The calling class will normally be in some package on the classpath, say com.hello.somepackage.SomeClass. So if SomeClass tries to call the getclass getresource without the /, the search will begin from the location of the class, which is in the package.
The are just some things to consider when using resources/images. But the first couple points should get you going.

How do I access a .gif file in a package in the src folder?

I'm working on a Java program using Eclipse. Right now, I have an src folder that contains 2 packages: memory.views and memory.resources.
In the memory.views package, I have my Main.java file. In the memory.resources package, I have my .txt file and .gif file.
Within the program, I have no problem accessing (and manipulating) the .txt file by using the path /memory/resources/name.txt. However, when I do the same with the .gif file using the code below, I get no result:
ImageIcon icon = new ImageIcon("/memory/resources/name.gif");
There's no error produced. The only effect is that I see no image when the program is running.
I've tried also writing the following, but none worked:
ImageIcon icon = new ImageIcon("/resources/name.gif"); <br>
ImageIcon icon = new ImageIcon("name.gif");
Now, just so nobody says that it's the .gif file's fault, I've actually entered in the full Finder path (I'm using a Mac) and that worked perfectly:
ImageIcon icon = new ImageIcon("/Users/[...]/src/memory/resources/name.gif");
However, I don't want to do the full path, because if I export the program and run it on another computer, then the non-programming computer won't display the image either.
So, right now, I don't even know what the problem is. The .gif file works sometimes, but not when it's accessed via the same path as the .txt file, which works all the time. I tried looking here (Cannot access resource by using the getResources() method), but it seems like he had a slightly different problem from me.
You can use
URL url = ClassLoader.getSystemResource("name.gif");
ImageIcon icon = new ImageIcon(url);
provided that your name.gif file ends up in classpath after compilation/build.
What is this ImageIcon class? Is it your own code?
Try Thread.currentThread().getContextClassLoader().getResourceAsStream("/memory/resources/name.gif");
See if this works...
File file = new File("/memory/resources/name.gif");
ImageIcon icon = new ImageIcon(file.getAbsolutePath());

What is the correct path for Toolkit.getImage()?

I need to upload an image file and generate a thumbnail for the uploaded file in my JSF webapplication. The original image is stored on the server in /home/myname/tomcat/webapps/uploads, while the thumbnail is stored in /home/myname/tomcat/webapps/uploads/thumbs. I'm using the thumbnail generator class I copied from philreeve.com.
I have successfully uploaded the file with help from BalusC. But using Toolkit.getImage(), I can't access the image.
I used the uploaded file's absolute path, like so:
inFilename = file.getAbsolutePath();
The relevant code from the thumbnail generator is:
public static String createThumbnail(String inFilename, String outFilename, int largestDimension) {
...
Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
return "Error loading file: \"" + new File(inFilename).getAbsolutePath() + "\"";
}
...
}
Since I am already using the absolute path, I don't understand why it is not working. I have also used the following values for inFilename, but I always get the "Error loading file...".
/home/myname/tomcat/webapps/uploads/filename.ext
/uploads/filename.ext
But I did check the directory, and the image is there. (I uploaded using /home/myname/tomcat/webapps/uploads/filename.ext, and it works.) What is the correct path for the image in that directory? Thank you.
Update
I got the code to work by using:
Image inImage = ImageIO.read(new File(inFilename));
I still don't understand why Toolkit.getImage() does not work though.
Are you sure it's a JPEG file? Use an image viewer to make sure nothing bad happened to the file during upload (or that it was an image to begin with).
Also, use new File(inFilename).exists() to make sure the path is correct. I also suggest to print new File(inFilename).getAbsolutePath() in error messages because relative paths can hurt you.
That said, the rest of the code looks correct.
The problem is that Toolkit.getImage() does not return the image immediately. The issue is well-described in this bug report, a relevant extract of which is here:
This is not a bug. The submitter is not properly using the asynchronous
Image API correctly. He assumes that getImage loads all of the image's bits
into memory. However, it is well documented that the actual loading of
bits does not take place until a call to Component.prepareImage or
Graphics.drawImage. In addition, these two functions return before the
Image is fully loaded. Developers are required to install an ImageObserver
to listen for notification that the Image has been fully loaded. Once they
receive this notification, they can repaint the Image.
I found that the answer to this question works well:
Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();

Categories