I want to create a Java class that I use to export images. This class will be exported in .JAR file which will allow me to integrate it directly into another project by passing as input parameter the name of the file and in return I would have this image in PNG format.
That's what I tried:
package militarySymbolsLibrary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class MainEntry {
public static void main(String agrs[]) {
}
public static BufferedImage generateImage(String symbolCode) {
File imageFile = new File("/pictures/SSGPU-------.png");
BufferedImage image;
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
image = null;
e.printStackTrace();
}
return image;
}
}
Pictures are stocked in folder pictures like this treeview below:
src
MainEntry.java
pictures
SSGPU-------.png
Then I export this class in .JAR file, I add it to my other program, I pass a parameter (picture's name except for this test) and normally my class return PNG file. But I have an error telling me that the file path is not the rigth one.
How can I solve this problem?
Thank you
Related
I have the following package hierarchy:
base--images--img.png
|
--code--Foo.java
|
--Base.java
That is, I have a package base which has 2 subpackages, base.images and base.code with respective files in each. Base.java just calls a method in Foo.
All of this gets bundled into base.jar when I build.
The problem: How can Foo.java load img.png no matter where the jar is located or run from?
Some things I've tried:
new File("../images/img.png")
Foo.class.getResource("../images/img.png")
Neither of these work because the "../images/img.png" is appended to the path the JAR is run from, not the path of the class.
MWE:
In Foo.java:
package base.code;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Foo {
public static void main(String[] args) {
URL url = Foo.class.getResource("/graphs/1.png");
try {
BufferedImage img = ImageIO.read(url);
} catch (IOException e) {
System.err.println("Image not found!");
}
}
}
In Base.java:
package base;
public class Base {
public static void main(String[] args)
Foo.main(args);
}
}
Resources are on the class path, never use a File. They might be stored in the jar (zip format).
The solution is simply to use an absolute path. That is more clear than a class package's relative path.
Foo.class.getResource("/base/images/img.png")
I need put one specific image from my project to specific folder in Java. Thanks for helping.
Edit:
Im creating a folder with File and the folder I'm creating i need to put an image i have in resources. Thanks for helping.
You can use NIO package in Java 7 with the class Files and the static method copy.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Main_copie {
public static void main(String[] args) {
Path source = Paths.get("data/image1.png");
Path destination = Paths.get("MyFolder/image1_copied.png");
try {
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Do you mean to copy the file from 1 location to another? If so, then the approach would be to create a new File at the desired location, create a FileOutputStream and write everything from the original File (using an FileInputStream) to this OutputStream.
Maybe this post can help you out.
I've got an issue with my .jar file. It runs fine in Eclipse but as soon as I export it, it won't open. I've checked the manifest file and it looks like it's okay.
I've tried exporting it as a runnable jar, as well as just using the jar builder. Nothing worked.
I've tried to run it in command prompt and it says it can't access the jar file... I've searched around a while on here and haven't found an answer yet.
I'm not sure what I'm doing wrong. The only thing I can think of is I'm not getting my images correctly.
I'm using .png files for the program's sprites and here's an example of how I get them for my program.
This code begins the building of a level from a .png file.
public class SpawnLevel extends Level{
public SpawnLevel(String path) {
super(path);
}
protected void loadLevel(String path){
try{
System.out.println("classpath is: " + System.getProperty("java.class.path"));
BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path));
int w = width = image.getWidth();
int h = height= image.getHeight();
tiles = new int[w*h];
image.getRGB(0,0,w,h,tiles,0,w);
}catch(IOException e){
e.printStackTrace();
System.out.println("EXEPTION FOUND!!! Could not load the level file!");
}
}
protected void generateLevel(){
System.out.println("Tiles: " + tiles[0]);
}
}
I've made one other .jar before for another program and didn't have a problem. Any help would be greatly appreciated.
If it helps, I used this code to display the resource folder path information.
System.out.println("classpath is: " + System.getProperty("java.class.path"));
Here's what my current path for my resources folder looks like. Before I export it from eclipse.
classpath is: C:\Users\name\workspace\Rpg_Game\bin;C:\Users\name\workspace\Rpg_Game\res
After I export to .jar
classpath is: 2ndGameTest.jar
If your images are in your resources package in the src The path you should be using for getResource() is something like
class.getResource("/resources/levels/level1.png")
UPDATE with test program
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class TestImage {
public static void main(String[] args) throws IOException {
Image image = ImageIO.read(TestImage.class.getResource("/resources/images/image.png"));
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(null, label);
}
}
I have a requirement to capture photos using system webcam. For this, I'm using webcam capture library. It contained three jar files. I wanted to package every thing including dependency jars in single jar application.
So, I sorted to unpack the dependent jar files place them in the src folder of netbeans project.
So, I extracted them. Two of them start with the same package name org, so I extracted and merged them. Important third package starts with com package. I've placed these three directories in src folder of my netbeans project.
Now the problem is that netbeans, says that package doesn't exist. But, the same project when compiled from command line in windows. It compiled and ran successfully, everything was working fine.
But, when I added the problematic library as a jar to the project, it worked fine, only extracting and placing it in src folder causing the problem.
Why is this error occurring and why in netbeans only, how to resolve this problem?
My code:
package screen;
import com.github.sarxos.webcam.*; **//Error here**
import com.github.sarxos.webcam.log.*; **// Error here**
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Util extends TimerTask{
private String filePath;
private String type;
private Timer timer;
private Webcam webcam;
public Util(String path,String type){
this.timer=new Timer("Capture Timer");
this.filePath=path;
this.type=type;
this.webcam=Webcam.getDefault();
}
public void capture() throws IOException{
if(webcam!=null){
webcam.open();
BufferedImage image=webcam.getImage();
Date date=new Date();
ImageIO.write(image,type,new File(filePath+"_"+date.toString().replace(' ','_').replace(':','-')+"."+type.toLowerCase()));
webcam.close();
}
else{
webcam=Webcam.getDefault();
}
}
public void startCapturing(int period){
this.timer.schedule(this,0,period);
}
public void stopCapturing(){
timer.cancel();
}
public void run(){
try{
capture();
System.out.println("Doing");
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
Util u=new Util("n082430_","PNG");
u.startCapturing(60000);
}
}
How do I get the images I stored in my web pages folder out so I can read them into a buffered image?
I found many explanations online on how it works but it's so confusing!
Maybe someone could help me by explaining it to me in a scenario familiar to me?
This is my server folder tree:
I want to read PNG pictures from images in Web Pages from within my ItemStorage class.
Here's what that class looks like:
import java.util.ArrayList;
import java.util.List;
import be.pxl.minecraft.model.Item;
import com.sun.jersey.spi.resource.Singleton;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Singleton
public class ItemStorage {
private ImageStorage test;
private HashMap<String, Image> categories;
private HashMap<String, BufferedImage> images;
private List<Item> recipesList;
public ItemStorage() {
File directory = new File("/images");
if (directory.isDirectory()) { //FILE PATH NOT A DIRECTORY
BufferedImage img = null;
for (File f : directory.listFiles()) {
try {
img = ImageIO.read(f);
images.put(f.getName(), img);
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
}
}
}
recipesList = new ArrayList<Item>();
//BufferedImage air = getImage("air"); //TRIED DIFFERENT APPROACH, SEE getImage()
//Armor
recipesList.add(new Item(7, 2, getImage("diamond_boots"), "Boots (Diamond)",
"0,0,0,1,0,1,1,0,1", String.format("%d,%d", getImage("air"), R.drawable.diamond_ingot )));
}
public void setItems(List<Item> list) {
recipesList = list;
}
public List<Item> getItems() {
return recipesList;
}
#Path("/images")
#Produces("image/png")
public Response getImage(String imageName) { //TRYING TO HTTP TO THE IMAGE
BufferedImage img = null;
try {
File imageFile = new File(imageName + ".png");
img = ImageIO.read(imageFile);
return Response.ok(img).build();
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
} finally {
return Response.ok(img).build();
}
}
}
As you can see, I tried to call the images both through HTTP and a simple IO directory.
This is a restful server running under tomcat 7.0.41.0
Please collaborate.
what puzzles me with your approach is, that you access a file from within your service, that is supposed to be located at the "root" ("/") directory. This is not inside your application.
In the rest service, there is no "context", as you have it in the servlet world. You need to identify the images folder somehow using a config option. You can also check the documentation of your REST server to see how to access the MessageContext and HTTPRequest. Then you can use them to access your web-application's runtime folder and access the images.