Images not drawing in eclipse - java

I have a BufferedImage space; and I then try to initialize it by using the try-catch
try {
space = ImageIO.read(new File("simple-star-space-background-effect-footage-023768280_prevstill.jpg"));
}
catch(Exception e) {}
When I try using g.drawImage(space, 0, 0, 800, 600, null); It doesn't show up. I think it has something to do with Eclipse because when I used a basic text editor, it worked. Here is a screenshot of where my pics are relevant to the program. They are in the same directory "src" but no image shows up.
The Screenshot

Please use:
try {
File myImage = new File("simple-star-space-background-effect-footage-023768280_prevstill.jpg")
System.out.println(myImage.getAbsolutePath());
space = ImageIO.read(myImage);
} catch(Exception e) {
e.printStackTrace();
}
I assume your path to your image is not correct, since you expect to have it in your user.dir system-property.
Also you eat the exception, which causes you to not see what the root cause of your issue is.
Also my hint is to avoid inline code. Define variables, which can be much easier debugged in the eclipse debugger instead of a single long line, which does multiple executions (like your new File(...) inlined in reading the image)

Related

FIle saving path

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.

Safely close/remove file for ImageView in JavaFX

I have a JavaFX application which displays all images from a certain folder in a VBox. The VBox is built like this:
try (DirectoryStream<Path> stream = Files.newDirectoryStream(imagePath)) {
for (Path file : stream) {
String fileNameLc = file.toString().toLowerCase();
if (fileNameLc.matches(".*\\.(jpg|png)")) {
ImageView graph = new ImageView(new Image(Files.newInputStream(file)));
graph.setPreserveRatio(true);
imageVBox.getChildren().add(graph);
}
}
} catch (IOException ex) {
//
}
There also is a button to remove all images (and all other files) in the folder which are displayed in the VBox. This is the code for the button action:
imageVBox.getChildren().clear();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(imagePath)) {
for (Path file : stream) {
Files.delete(file);
System.out.println("Removing: " + file);
}
} catch (IOException ex) {
//
}
Displaying the images works fine, but deleting them does not work. In the standard output I see
Removing: /foo/img1.jpg
Removing: /foo/img2.jpg
...
No Exceptions are thrown, but the image files are still there if check the contents of the folder. All files in the folder which are not images (and are not displayed in the VBox) are removed succesfully, but the images displayed in the VBox are not.
I thinks the cause is that after
imageVBox.getChildren().clear();
a background thread starts to remove the images and the .clear() method returns immediately. This way the code block which removes the files is executed before the Image resources are closed.
What would be be the best way to close the images? and why is there no Exception thrown by the Files.delete() method?
I know it's a realy old question, but i think anyone can have the same problem, i have it few days ago.
The problem is realy simple when you create yout ImageView, the image are load by JAVA, and you can't delete it before free the memory.
I don't know why they are no error, but you can see an error if you try to delete
the image file manualy during the execution of jar.
For free the ImageView you have to do that :
Image graph = new Image(Files.newInputStream(file));
ImageView graphView = new ImageView(graph);
graph = null;
graphView.setImage(null);
System.gc();
Don't forget System.gc(), that will call the garbage collector and he will free memory and after that you can now delete the file.
Enjoy,
Sorry for the realy bad english

Having trouble loading image to screen

I am making a game and I am stuck trying to get the image to screen. I states that-
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
I am sure that my image path is the right path, but it keeps stating that it's not.
background = new Background("C:/hello/flappybird.png");
The "debug" section of my workspace states that there is a problem with
background.render(g);
specifically, with
g.drawImage(img,(int)x,(int)y,null);
and I have no idea why it is doing this. I am 100% sure my build path is right!
EDIT: just incase you want to know the constructor of the background class:
public Background(String s) {
try {
img = ImageIO.read(this.getClass().getResource(s));
} catch (IOException e) {
e.printStackTrace();
}
}
This error indicates the image file wasn't found. To be sure that this is really the case, I urge you to execute ImageIO.read() directly and check the result:
BufferedImage icon = ImageIO.read("C:/hello/flappybird.png");
Also, it's not a good practice to use resources outside the classpath. I strongly suggest you to change your class Background to use classpath resources. Somewhere inside your Background class, you could add:
public class Background {
public Background(String filename) {
// Some code here
BufferedImage image = ImageIO.read(getClass().getResource("/resources/images/" + filename));
// More code here
}
}
I have found a solution!
it seems that in gamePanel, after I declared my BufferedImage, I forgot to add-
Graphics g = image.getGraphics();
sorry guys, I feel so stupid XD

Why is there no image when running from a .jar file?

I'm trying to make my panel show image as background. I already can do that in NetBeans, but when I build my jar and run it image doesn't show there. I know I have to access it differently. I have seen many tutorials but every one of them shows how to do it with ImageIcon, but I don't need that, I need just Image. Can anyone point out what piece of code do I need to do this? Thanks.
This is my code for backgrounded JPanel:
public class JPanelWB extends JPanel { // Creates JPanel with given image as background.
private Image backgroundImage;
public JPanelWB(String fileName){
try {
backgroundImage = ImageIO.read(new File(fileName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, getWidth(),getHeight(),this);
}
}
Yeah, you're trying to read in the image as a file -- don't do that since files don't exist within a Jar file. Instead read it in as a resource.
Something like so:
public JPanelWB(String resourceName){
try {
// backgroundImage = ImageIO.read(new File(resourceName));
backgroundImage = ImageIO.read(getClass().getResource(resourceName));
} catch (IOException ex) {
new JDialog().add(new Label("Could not open image."+ex.getMessage()));
}
}
But note that resource path is different from file path. The resource path is relative to the location of your class files.
If you want to read new image and import it as background, people smarter than me already answered your question.
But, if your problem is similar to mine, then this migh help:
If you already have images to show, then the point is to call them from absolute path. Executable class form JAR will read drive created inside virtual machine, not the physical drive in your computer.
Put images in short-pathed folder like
C:\J\proj\img\
and call them with absolute path like
"C:\\J\\proj\\img\\your_image.png" // (Don't forget the double backslashes.)
(If you don't mind path lenght, leave them in image folder inside your project package, and call them from there.)
NetBeans will pack them into JAR with absolute path. On execution JRE will create JVM with that path in it, take the images from JAR and put them to that virtual path. Class will be able to find them, because it doesn't read path from physical drive, but from own virtual one newly created inside JVM.
In that case avoiding ImageIcon is just more clutter, not less.
You can add "blackBoard" as JLabel to be background to your JFrame, set its layout to null, something like this:
private JLabel blackBoard;
private JLabel noteToSelf;
//.....
blackBoard = new JLabel();
noteToSelf = new JLabel();
//.....
// putting JLabel "blackBoard" as background into JFrame
blackBoard.setIcon(new ImageIcon("c:\\Java\\images\\MarbleTable.png"));
getContentPane().add(blackBoard);
blackBoard.setBounds(1, 1, 400, 440);
blackBoard.setLayout(null);
and then add components into "blackBoard" instead of your JFrame, like this.
// putting JLabel "noteToSelf" onto background
noteToSelf.setIcon(new ImageIcon("c:\\Java\\images\\Sticker_a1.png"));
// or: noteToSelf.setText("Remind me at 6:30am...");
blackBoard.add(noteToSelf);
noteToSelf.setBounds(noteX, noteY, 64, 48);
Now your JFrame is table board and "blackBoard" is table sheet on it.
Hope this helps.

Problem converting Java applet to Jar. Maybe Image loading problem

I'm writing an applet in eclipse and under the eclipse environment it works well.
while creating a jar file from this project, the problems start.
After testing the jar with several options, I think the problem is with loading an image from a web page.
Any Other features from the applet seems to work ok in the jar.
The code of loading image in my project looks like that:
MediaTracker mt = new MediaTracker(this);
String photo = imagePath
URL base = null;
try {
base = getDocumentBase();
}
catch (Exception e) {
}
if(base == null){
System.out.println("ERROR LOADING IMAGE");
}
Image imageBase = getImage(base,photo);
// Some code that works on the image (not relevant)
// The rest of the code
icon.setImage(image);
imageLabel.setIcon(icon);
But the jar can not load the imgae and it doesn't disply it in while running and the applet is stuck because of that. (unlike in the eclipse, which loads the image and shows it)
What could be the problem?
A second problem is that from the applet in the eclipse the loading take few seconds. Is there a way to speed things up?
Thanks for any help,
I have no idea how this could be working in Eclipse.
The problem is that getDocumentBase() returns location of a page, in which the applet is embedded (e.g. http://some.site.com/index.html), and you are trying to load a picture from that location. Obviously, there is no picture, just an html (or php) file, and the loading fails.
If your goal is to load an image from inside the jar, try:
Image img = null;
try {
img = ImageIO.read(getClass().getResource("/images/tree.png"));
} catch (IOException ex) {
System.err.println("Picture loading failed!");
}
where "/images/tree.png" is path to image file in your source tree.
EDIT: If you need just to load an image from URL, you can use:
Image img = null;
try {
img = ImageIO.read(new URL("http://some.site.com/images/tree.png"));
} catch (IOException ex) {
System.err.println("Picture loading failed!");
}
This method is a bit better than Applet.getImage(new URL(...)) - I had some problems when loading many images.

Resources