public void loadStdImage() throws IOException
{
Image image = ImageIO.read(this.getClass().getResource("/Resources/Images/Student/Capture.png")); //Line 350
ImageIcon icon = new ImageIcon(image);
JLabel lblImage = new JLabel(icon);
lblImage.setIcon(icon);
lblImage.setBounds(753, 50, 149, 171);
add(lblImage);
}
I tried many things... but nothing works out. Continuously showing the following run-time error
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at View.Student.loadStdImage(Student.java:350)
Project folder structure is:
edit:
Found the solution. See the change of icon of the resource folder in the following picture and the above image. I added my resource folder to Java Build Path. Right click on your project, go to properties, then select 'Java Build Path', from there add your folder to java build path.
Cheers
enter image description here
welcome to SO. As you are new here, please read this - https://stackoverflow.com/help/mcve
Let me help you with this for now.
I have standard Eclipse project:
and my test class looks like (minimal):
package q34460547;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LoadTest {
public static void main(String[] args) throws IOException {
new LoadTest().loadStdImage();
}
public void loadStdImage() throws IOException {
Image image = ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
}
}
and now, when I used
ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
image is loaded from res so called source folder in Eclipse.
When I used
ImageIO.read(this.getClass().getResource("ScreenShot005.png"));
image s loaded from the folder in which LoadTest.java file is (to be precise it is also compiled to same folder - in Eclipse it's bin).
You can find more info for example here - What is the difference between Class.getResource() and ClassLoader.getResource()?
edit:
The image has to be on classpath (when using Class.getResource), that's why it was not loaded from Resources folder. There are two options, use another version of ImageIO.read() or make your Resources folder a source folder:
Related
ok i am a new one here and tried to write an awesome program:
package f;
import javax.swing.*;
public class dasMain {
public static void main(String[] args) {
ImageIcon img = new ImageIcon("pics/daFaq.png");
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
the thing is that if I run the program from Intellij Idea, then everything works fine, but after compilation the picture disappears
here are the source files of the project:
https://i.ibb.co/Njc8jYp/screen.png
i want to run this awesome code with pictures on other computers, but i only know this way and it doesn't work :(
You probably do not know where your program expects the picture to be. If you modify your code slightly, this information would be evident. Make use of
ImageIcon(URL)
File.toURI()
URI.toURL()
With that your code can look like this:
package f;
import javax.swing.*;
import java.io.File;
public class dasMain {
public static void main(String[] args) {
File png = new File("pics/daFaq.png");
System.out.println("Loading image from " + png.getAbsolutePath());
ImageIcon img = new ImageIcon(png.toURI().toURL());
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
Also I am pretty sure you intend to ship the png together with your code, so you better load it as a resource from the classpath. Here is an example.
I also investigated a bit why you would not see any error message or exception. This is documented in ImageIcon. So you might want to verify the image was loaded using getImageLoadStatus().
If you access the resource with the path like pics/file_name.png, then the pics - is the package name. And it must be located in the directory, marked as resource type. For example, create the directory, named resources in your project root, mark this directory as resource type, and move the pics there:
P. S. I would advise to use Maven or Gradle build system for managing project builds. As it is commonly accepted build management systems for the JVM projects. IDE New Project Wizard has the option to create Maven or Gradle based projects.
This question already has answers here:
file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true
(17 answers)
Closed 2 years ago.
I am currently busy with building a simple javafx application. In this application, you can add and remove .jar files from within the application, from which I am gathering some information. One of the things I use from these .jar files are textures stored as images.
Whenever I load an Image using a path from the jar file, I am unable to remove this .jar file later on. This is quite logical as the .jar file is now being used by this Image, but for some reason, I am unable to delete the .jar file from within the application even when removing all references to this Image and calling the garbage collector.
The way I am currently trying to delete the file is the following:
File file = new File("mods/file.jar");
file.delete();
At some point in the application I initialize the image as follows:
Image block = new Image(pathToJar);
I have tried the following things to resolve my problem:
Set block = null; and call System.gc();
Call Image.cancel() and call System.gc();
I have also tried the above in combination with System.runFinalization();
I tried removing the .jar file when the stage is closing in hopes of everything being unloaded, but without success.
At this point in time, I am not quite sure why I am unable to actually delete the .jar file. Could anyone possibly explain to me why this is the case and how it could be resolved? Many thanks in advance!
EDIT: the purpose of the application was not clear enough. I am making a color picker that takes average colors of textures from .jar files (Minecraft mods). These .jar files are to be added and deleted from the application in a flexible way. Once you do not want to consider textures of a certain .jar file anymore, you just remove it from the application and be done with it. For ease of use, I made copies of the .jar files so I can access them relatively. Once you are done with the .jar file I want to remove this copy as it will just take in unnecessary storage.
I have narrowed the problem (thus far) down to the initialization of an Image. On request, here a MRE:
public class example extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
// Read image, needed at some point in my code
Image block = new Image("jar:File:./mods/botania.jar!/assets/botania/textures/blocks/alfheim_portal.png");
// Make it so that jar is not used anymore
block.cancel();
block = null;
System.gc();
// Try to delete the file after being done with it
File delete = new File("mods/botania.jar");
Files.delete(delete.toPath());
}
}
After initializing the image, and thereafter removing references to it, it should be cleaned by the garbage collector (at least to my knowledge). Instead, now it just gives the following error:
Caused by: java.nio.file.FileSystemException: mods\botania.jar: The
process cannot access the file because it is being used by another
process.
I can't reproduce the issue on my system (Java 14 on Mac OS X); however running it on Windows 10 with the same JDK/JavaFX versions produces the exception you describe.
The issue appears to be (see https://stackoverflow.com/a/54777849/2067492, and hat-tip to #matt for digging that out) that by default the URL handler for a jar: URL caches access to the underlying JarFile object (and doesn't call close(), even if an InputStream obtained from it is closed). Since Windows holds on to file handles in those situations, the underlying OS is unable to delete the jar file.
I think the most natural way to address this is to use the java.util.jar API (or just the plain java.util.zip API), which will give you far more control over closing resources than generating a URL and passing the URL to the Image constructor.
Here's a self-contained example using this approach, which works both on my Mac and on my Windows 10 virtual VM:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void init() throws Exception {
// create an image in a jar file:
BufferedImage image = new BufferedImage(100, 100, ColorSpace.TYPE_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(new Color(0xd5, 0x5e, 0x00));
graphics.fillRect(0, 0, 100, 100);
graphics.setColor(new Color(0x35, 0x9b, 0x73));
graphics.fillOval(25, 25, 50, 50);
JarOutputStream out = new JarOutputStream(new FileOutputStream("test.jar"));
ZipEntry entry = new ZipEntry("test.png");
out.putNextEntry(entry);
ImageIO.write(image, "png", out);
out.close();
}
#Override
public void start(Stage stage) throws Exception {
assert Files.exists(Paths.get("test.jar")) : "Jar file not created";
JarFile jarFile = new JarFile("test.jar");
JarEntry imgEntry = jarFile.getJarEntry("test.png");
InputStream inputStream = jarFile.getInputStream(imgEntry);
Image img = new Image(inputStream);
jarFile.close();
// The following line (instead of the previous five lines) works on Mac OS X,
// but not on Windows
//
// Image img = new Image("jar:file:test.jar!/test.png");
Files.delete(Paths.get("test.jar"));
assert ! Files.exists(Paths.get("test.jar")) : "Jar file not deleted";
ImageView iview = new ImageView(img);
Scene scene = new Scene(new BorderPane(iview), 200, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
I’m trying to solve this problem for about 2 days. I’ve to create runnable JAR. I’m using Eclipse (newest version), Java SE 10 on macOS Sierra.
So, this is the only class in the test project.
package test_package;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Tester {
public static void main(String[] args) {
try {
BufferedImage testImage = ImageIO.read(Tester.class.getClassLoader().getResourceAsStream("/test.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is test project file structure (without test.jpg file):
TestProject
- bin
-- test_package
--- Tester.class
- src
-- test_package
--- Tester.java
I tried four different options:
BufferedImage testImage = ImageIO.read(Tester.class.getResourceAsStream("test.jpg"));
BufferedImage testImage = ImageIO.read(Tester.class.getResourceAsStream("/test.jpg"));
BufferedImage testImage = ImageIO.read(Tester.class.getClassLoader().getResourceAsStream("/test.jpg"));
BufferedImage testImage = ImageIO.read(Tester.class.getClassLoader().getResourceAsStream("test.jpg"));
If test.jpg was placed in the root of the project, in src or test_package directory, the compiler always throwing the same error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
If I copy test.jpg to bin directory, this two options give the correct result:
BufferedImage testImage = ImageIO.read(Tester.class.getResourceAsStream("/test.jpg"));
BufferedImage testImage = ImageIO.read(Tester.class.getClassLoader().getResourceAsStream("test.jpg"));
But when I am trying to create Runnable JAR, the same error appears. When trying to create JAR, I copied test.jpg to each directory of the project.
I also tried to change option in Eclipse Library handling when creating Runnable JAR (I tried all three options for the project with all four command options). In each case the error appears.
About the Source directory. In my case, the source directory is src.
So, I don’t know what to do next. I tried almost everything with no result. Any ideas?
Optional<InputStream> resourceAsStream = Optional
.of(Thread.currentThread().getContextClassLoader().getResourceAsStream(
"/test.jpg"));
Try this to get a stream then it can be converted to image
It's the first day of learning JavaCV for me. And this is the first test example which I use just to make sure that my setup is done correctly. Unfortunately I can't run the example and I barely understand the code and all dependencies so it's really hard for me to find out what is missing. Below I'll post my project setup and also the errors I get.
Also the example I use is from: http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/javacv-capture-save-flip-show-live.html
code
import static com.googlecode.javacv.cpp.opencv_core.cvFlip;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.VideoInputFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class GrabberShow implements Runnable
{
//final int INTERVAL=1000;///you may use interval IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public GrabberShow()
{
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
#Override
public void run()
{
FrameGrabber grabber = new VideoInputFrameGrabber(0); // 1 for next camera
int i = 0;
try
{
grabber.start();
IplImage img;
while (true)
{
img = grabber.grab();
if (img != null)
{
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++) + "-aa.jpg", img); // show image on window
canvas.showImage(img);
}
//Thread.sleep(INTERVAL);
}
}
catch (Exception e)
{
}
}
}
I use Eclipse and it seems like all imports are there.
Here is a print screen of my project as it looks like in Eclipse:
So this is it for the setup. I try to get something out of this. When I right click on the project and try to Run it as Java Application the following windows is showing up:
You can see my choice at the top of the window. The I get an error window A Java Exception has occurred and here is part of the error I get in the console window:
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Users\Xman\AppData\Local\Temp\javacpp4929678155627\jniopencv_core.dll: Can't find dependent libraries
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.load0(Unknown Source)
at java.lang.System.load(Unknown Source)
at com.googlecode.javacpp.Loader.loadLibrary(Loader.java:422)
at com.googlecode.javacpp.Loader.load(Loader.java:372)`
I've read the error, it seems like the problem is caused by missing libraries but I'm not sure, also I have followed the instructions (which weren't that many in fact) and from the comments below the example code it seems that it actually works. So I guess the problem is somewhere here - in my project, code, setup, but I can't find what I'm missing or doing wrong.
This error occurs when your opencv dll are not set in System path.
If you have extracted your opencv folder in C:\ directory then set your path as following
For 32 bit:
C:\opencv\build\x86\vc10\bin;C:\opencv\build\common\tbb\ia32\vc10\
For 64 bit:
C:\opencv\build\x64\vc10\bin;C:\opencv\build\common\tbb\intel64\vc10\
If you have extracted in different location then change the path accordingly.
In order to set path you can go to Control Panel > System Security > System > Advanced System Settings > Environment Variables. In System variable select path and click on Edit and insert above locations and restart windows.
you can find detailed instructions at http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Download and install : Microsoft Visual C++ redistributable package (32-bit): vcredist_x86.exe
I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar.
I found the getClass().getClassLoader().getResourceAsStream() method online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well..
I`d be very thankful for any help.
Edit:
Here is a picture of how the directory is organized:
My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it.
Here is the inside of the jar:
again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out.
A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files.
If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it.
For instance, say your package structure looked like this:
So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so:
package codePackage;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ClassUsesResources {
private JLabel label = new JLabel();
public ClassUsesResources() {
try {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
"images/img001s.jpg"));
ImageIcon icon = new ImageIcon(img);
label.setIcon(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
new ClassUsesResources();
}
}