Class path resource for JLabel ImageIcon - java

I want to add a image in JLabel that can display after building the project too in eclipse.
I have this code..
jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));

Goodness, why are you trying to read an image file in one line?
First, make sure that your resources folder is defined for your project and is on the build path.
Here's an example from one of my Java projects.
Next, code a method to read image files from the resources folder.
private Image getImage(String filename) {
try {
return ImageIO.read(getClass().getResourceAsStream(
"/" + filename));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Read the image file once, saving the result in a class variable ImageIcon.
imageIcon = new ImageIcon(getImage("image.png"));
Finally, reference the ImageIcon in your Swing code.
jLabel1.setIcon(imageIcon);

Related

ImageIO.read unable to find .png-file

sorry if this has been asked quite a few times, I'm new here.
I've used three different approaches to get a file to be loaded and nothing worked:
Using Toolkit:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("apple.png"));
Using a File:
BufferedImage img = null;
try {
img = ImageIO.read(new File("apple.png"));
} catch(IOException e) {
e.printStackTrace();
}
Using a FileInputStream:
Path path=Paths.get(".").toAbsolutePath().normalize();
String dir=path.toFile().getAbsolutePath()+"\\resources\\apple.png";
BufferedImage image = null;
try {
image = ImageIO.read(new FileInputStream(dir));
} catch(IOException e) {
e.printStackTrace();
}
path and dir are working fine getting me an absolute path but I alway end up with image = null.
/edit:
#DuncG: I don't get an exception so there's no stacktrace to post, sorry. new File("apple.png").exists() evaluates to false.
#Harald_K: It is a normal .png image-file I have on my local system. It is located in src/main/resources/apple.png.
The issue is that your program is NOT able to find the required file and then further read it as an Image. This is a common recurring problem statement in any modern-day app where a required resource is NOT found, halting subsequent operations.
I would suggest writing a common piece of code to always locate such files/resources in your project dir just by giving the filename and returning the path.
#Slf4j
public class PathFinder {
private static Path filepath;
public static Path getFilePathForFile(String filename) {
log.info("Looking for filepath for given filename: ".concat(filename));
try {
filepath = Files.walk(Paths.get("."))
.collect(Collectors.toList()).stream()
.filter(file -> !Files.isDirectory(file) &&
file.getFileName().toString().startsWith(filename))
.findFirst().get();
} catch (IOException exception) {
log.error(exception.getMessage());
} return filepath;
}
}
Now you can easily use the above Pathfinder utility class to look for any given file and further operate on it as shown below:
BufferedImage img = ImageIO.read(PathFinder.getFilePathForFile("apple.png")
.toFile());

Image/File upload path after making app in Java from Eclipse

I am making a Java-SQL database storing app on Eclipse and MySQL. In this app, I have to upload image to the file directory. Currently while making this app, I am using an image upload path and storing all the uploaded images there. But when I'm finished with the app, and if I'm to work it on someone else's computer the image upload path in the code obviously will not work on that computer. What shall I do to make it work on other computer as well? Should I make a prompt which asks for image upload path every time the app opens and store that, or something else?? please help.
private String imageUploadPath = "/home/tsoprano/Documents/eclipse-workspace/enable/src/com/enable/regis/imgupload/";
File file1;
picLabel = new JLabel(" Upload Photo");
picLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser imageChooser= new JFileChooser();
if(imageChooser.showOpenDialog(picLabel)==JFileChooser.APPROVE_OPTION) {
file1 = imageChooser.getSelectedFile();
ImageIcon icon= new ImageIcon(imageChooser.getSelectedFile().getPath());
Image img=icon.getImage().getScaledInstance(130, 150, Image.SCALE_SMOOTH);
icon= new ImageIcon(img);
picLabel.setIcon(icon);
}
}
});
//inside the submit button action
String filePath = imageUploadPath + file1.getName();
try {
BufferedImage bi = ImageIO.read(file1);
ImageIO.write(bi, "jpg", new File(filePath));
} catch (IOException e1) {
e1.printStackTrace();
}
rdto.setPicUrl(filePath);
I would not suggest doing this via a config file, because this is not very user-friendly. Instead, get the current directory (i. e. the one that you executed the java command) using System.getProperty("user.dir"). Then create a new folder inside there, and use it as your upload folder. This will make sure you always have a useable path without bothering the user with specifying it.

i am not able to get the images read in java for exporting it as JAR

This code throws a NullPointerException and I have no idea why.
try {
imageIcon = new ImageIcon(ImageIO.read(new File("res/Background.png")));
backgroundImage = imageIcon.getImage();
signIn = new MyButton("SignIn", ImageIO.read(new File("res/SignIn.png")), ImageIO.read(new File("res/SignInHover.png")));
signUp = new MyButton("SignUp", ImageIO.read(new File("res/SignUp.png")), ImageIO.read(new File("res/SignUpHover.png")));
back = new MyButton("Back", ImageIO.read(new File("res/Back.png")), ImageIO.read(new File("res/BackHover.png")));
exit = new MyButton("Exit", ImageIO.read(new File("res/Exit.png")), ImageIO.read(new File("res/ExitHover.png")));
} catch(IOException e) {
JOptionPane.showMessageDialog(null, "");
}
res/ is a source folder in the project root which contains all images used in this piece of code but I'm not able to get it to work. I've tried using getClass().getResource() (which works from inside Eclipse but not from a .jar file) and getClass().getResourceAsStream() (which throws an exception telling that the input stream is null) but to no avail.
P.S.: MyButton is a user-defined class which extends JButton and has a constructor MyButton(String, final BufferedImage, final BufferedImage).
After all I succeeded by just making images folder under my source(i.e. under res) folder. And using method
ImageIO.read(getClass().getResource("/images/SignIn.png"));

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

Loading Image in Java Applet

When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed

Categories