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
Related
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());
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);
Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?
I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U
The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);
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));
Im Trying to load my images on to Java but when running the code nothing appears inside my JFrame.
The way im doing it is calling my Image function from my main:
import java.awt.*; // Graphics stuff from the AWT library, here: Image
import java.io.File; // File I/O functionality (for loading an image)
import javax.swing.ImageIcon; // All images are used as "icons"
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
And then calling it here:
GI_Background = GameImage.loadImage("Images//background.jpg");
GI_DuskyDolphin = GameImage.loadImage("Images//DuskyDolphin.jpg");
If this is not enough information I'll gladly supply the rest of the code :)
Thanks
If the image is part of the application, do not use a File but use the java resource mechanism.
URL imageUrl = getClass().getResource("/Images/background.jpg");
return new ImageIcon(imageURL).getImage();
The resource URL will return null when not found.
If the application is packed in a .jar, you can open that with 7zip/WinZip or so, and check the path. It must be case-sensitive, and using / (not backslash).
I'm not quite sure what you try to achieve...
to load an image with a method, this will be enough:
private Image loadImage(String fileName){
return (new ImageIcon(fileName)).getImage();
}
Afterwards, i would create a JLabel with the Image as background;
ImageIcon image = getImage( filename );
JLabel imageLabel = new JLabel( image );
imageLabel.setSize( image.getIconHeight, image.getIconWidth );
JFrame frame = new JFrame();
frame.add( imageLabel );
Try this and feel free to aks again if i does not work for you, or thats not want you want :)