Trouble deploying jar file with images - java

I am trying to deploy my Java GUI as a runnable jar file. The problem is that none of the images or even the shapes I've created with Swing & AWT show up when I run the jar file. Can anyone tell me the proper way to export a Java application with images and shapes? The following code calls in random images.
int randomImage = (int)(Math.random() * 8);
try {
image = ImageIO.read(new File("src/images/" +randomImage + ".png"));
} catch (IOException e) {
e.printStackTrace();
}

By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL. Namely:
URL url = this.getClass().getResource("/path/to/the.resource");

Related

JAR file not running when adding images

I was having problems exporting the pictures into the JAR file and after some browsing i found some sollution, but it doesn't seem to be working
try {
//leftFoot = ImageIO.read(new File("resources/leftFoot.png"));
//rightFoot = ImageIO.read(new File("resources/rightFoot.png"));
URL url = this.getClass().getResource("/resources/leftFoot.png");
leftFoot = ImageIO.read(url);
url = this.getClass().getResource("/resources/rightFoot.png");
rightFoot = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
So, if i try to upload the items from the first two lines(and comment the following 4), the main GUI stuff runs in the JAR file but the images ar not shown. If i do it the other way round(the code above), no GUI element works in the jar file. I have a "resources" folder containing the pictures both in the "bin" folder and in the main folder along bin,src,settings etc. cause i read somewhere that this is how it supposed to be, although i do not know why. leftFoot and rightFoot are BufferedImage objects. Could you tell me what is not working here?

Servlet interaction with filesystem: storing files and generating URLs for clientside access

SUMMARY
I need to store both uploaded and server-generated images, with portable and
predictable paths so my server code is aware of where these images exist.
I need to generate URLs to these images that can be sent to the client. These URLs will be used in HTML image elements.
PROBLEM
My web application allows the user to upload an image, using gwtupload(Apache Commons). This image is stored on the server and a URL returned to the client so the image is shown. gwtupload provides a clientside method to get this URL for the uploaded image. This works in deployment; the following aspects do not:
In certain cases, the uploaded image must be cropped. This results in
a new image being generated by a servlet method. I want to store this
cropped image and return(to the client) an access URL.
Then, this image is used by another method to generate another
image. This method must know the location on the file system of
the previously uploaded(and/or cropped) image. A URL for the new
image must then be returned to client.
I have implementation working perfectly in GWT development mode. However, as I expected, after deployment to my own Tomcat server, the remote services fail due to my confusion regarding the file system. I do not know the correct way of storing these images in a predictable place on the server filesystem, nor do I know how to generate access URLs(for files residing outwith the WAR, as these images will.)
All these images are only needed for the current session, so the locations can be temporary directories. I have spent two days experimenting and trawling the web for a solution to no avail.
I will post abridged code below. This is my attempt to simply use the working directory and relative pathnames. Using the Eclipse debugger attached to my servlet container, I could see the results of String dataDir = context.getRealPath("foo") indicating a temp folder within the servlet: but when I navigated there using explorer, NONE of the files had been written to the disk. I am very confused.
public String[] generatePreview(String xml) {
PreviewManager manager = new PreviewManager();
String url;
try{
preview = manager.generatePreview(xml);
}
catch (Exception e){e.printStackTrace();}
//Create the preview directory
File folder = new File("previews");
if (!folder.exists()) folder.mkdir();
//The file to be written to
File output = new File(folder, "front.jpg");
ServletContext context = getServletContext();
String dataDir = context.getRealPath("previews");
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
url = "previews/" + output.getName();
return url;
}
#Override
public String cropBackground(int[] coord_pair, String relativePath) {
File backgroundsFolder = new File("backgrounds");
if (!backgroundsFolder.exists()) backgroundsFolder.mkdir();
ServletContext context = getServletContext();
String dataDir = context.getRealPath("backgrounds");
File current = new File(relativePath);
String croppedName = "cropped_" + relativePath.replace("./backgrounds/", "");
int x = coord_pair[0];
int y = coord_pair[1];
int width = coord_pair[2];
int height = coord_pair[3];
String croppedPath = null;
try {
croppedPath = imageCropper.createCroppedImage(current, "backgrounds", croppedName, x, y, width, height);
}
catch (IOException e){
e.printStackTrace();
}
current.delete();
return "backgrounds/" + croppedPath;
I am aware that my current 'return' statements would never work in deployment: I need to generate the URLs properly and return as strings. I'm sorry about the question length but I wanted to make my problem clear.
Choose a directory where your images will be stored, outside of Tomcat. Assign some unique ID to each uploaded or generated image, and store the images in this directory (with the ID as file name, for example).
Generate URLs to an image servlet that will read the image by ID in this directory, and send the bytes of the image to the output stream of the servlet response : image.action?id=theImageId.

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.

Load Image from Jar: Always null

Looked at other posts on SO and they did not solve this issue.
I'm trying to load an image from my jar file. It is continuously coming up as null. The image is located under:
.Jar file > images > BLOCK.png
To load the image I am doing:
BufferedImage bImg;
URL url = getClass().getResource("/images/BLOCK.png");
try {
bImg = ImageIO.read(url);
} catch (IOException ex) {
Logger.getLogger(TileEngine.class.getName()).log(Level.SEVERE, null, ex);
}
url is null as is bImg.
Do not worry about case sensitivity as I've already checked that.
try this :
Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/BLOCK.png"));
Which jar file is the image in, compared with the class you're using to call getResource? If they're loaded by the same classloader, it should be fine.
Have you double-checked that the jar file actually contains the file?
Are you sure that your classloader is actually using the jar file at all (rather than .class files directly on disk, for example)?
If you have a short but complete program which demonstrates the problem, that would really help. (A console app would be ideal... we don't need to see the image, after all.)

how to read image from project folder in java?

I am developing web method for webservice in java. In this web method I have to read image from my images folder which resides in my webservice project folder. I am using the code as follows.
#WebMethod(operationName = "getAddvertisementImage")
public Vector getAddvertisementImage()
{
Image image = null;
Vector imageList = new Vector();
try
{
File file = new File("E:/SBTS/SBTSWebservice/web/adv_btm.jpg");
image = ImageIO.read(file);
imageList.add(image);
}
catch (IOException e)
{
e.printStackTrace();
}
return imageList;
}
I am unable to read image from images folder.I am getting error image file "input file can't read" at image = ImageIO.read(file); how to resolve this issue ? Is there any mistake in my code or is there any other way to read image ? if there is any mistake in my code then can you proide me the code or link through which i can resolve the above issue.
Is the E:\ drive mapped on your web server? The Java compiler has no idea that you might access files outside of its scope and how it could tell your web server to map a network drive or a local hard disk which is attached to your development computer.
The solution is to put the image file into the same directory as the Java source file and then use
InputStream in = getClass().getResourceAsStream("adv_btm.jpg");
Check that your IDE (or whatever you use to build your application) does copy the image file in the same directory where it creates the .class file. Then it should work.

Categories

Resources