I'm new here and kinda new to java.
I've encountered a problem.
I have a very simple program that tries to create pngs and save them in a user selected folder.
byteimage is a a private byte[]:
byteimage = bcd.createPNG(300, 140, ColorSpace.TYPE_RGB, Color.BLACK, Color.BLACK);
setPath() is called inside the action listener of the browse button
private void setPath() {
JFileChooser pathchooser = new JFileChooser();
pathchooser.setMultiSelectionEnabled(false);
pathchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
pathchooser.setApproveButtonMnemonic(KeyEvent.VK_ENTER);
pathchooser.showDialog(this, "OK");
File f = pathchooser.getSelectedFile();
if (f != null) {
filepath = f.getAbsolutePath();
pathfield.setText(filepath);
}
}
Byte to png method looks like this:
public void byteToPNG(String filename) {
try {
InputStream in = new ByteArrayInputStream(byteimage);
BufferedImage bufferedimg = ImageIO.read(in);
ImageIO.write(bufferedimg, "png", new File(filename));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
This method is called like this:
byteToPNG(pathfield.getText() + System.getProperty("file.separator") + textfield.getText() + ".png");
textfield.getText() sets the actual name of the png.
Inside the constructor, default filepath is set:
filepath = System.getProperty("user.dir");
pathfield.setText(filepath);
The code runs fine from Eclipse and it produces a png image at the desired location.
Unfortunately, after exporting as jar, it starts but when the button for generating the png is pressed, nothing happens. I'm thinking there's a problem at InputStream or BufferedImage, but I'm a bit puzzled.
If the String fileName passed to byteToPNG isn't absolute (i.e. written in the form "C:/foo/bar/etc") that could be the cause of the broken jar. You could also try running the jar file in the terminal using the command:
java -jar myJarFile.jar.
This will cause a console window to remain open alongside your running jar application in which all your applications output (including any exceptions) will be printed.
Related
The below code works when running from my editor but the image fails to load when compiled into a runnable jar file with eclipse.
public static BufferedImage getRandomImage() {
// returns a random image from the Images folder
Random rand = new Random();
URL res = Card.class.getResource("Images"); // located in /src/.../Images
File f = new File(res.getFile());
if (!f.exists()) {
return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}
File[] files = f.listFiles();
int random = rand.nextInt(files.length);
BufferedImage img = null;
try {
img = ImageIO.read(files[random]);
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
Could someone please suggest how I can modify my code or editor to load the files when compiled.
I have read other methods of accessing files but since I need to select randomly from a folder, I need to use the File class.
There is no safe way to list resources at runtime.
(Some people may suggest approaches which work sometimes, but will not work all the time. Class.getResource is not guaranteed to provide a listing; ProtectionDomain.getCodeSource can return null.)
But you don’t need to. It’s your application; you already know what files you put into it.
The best way is to either hard-code the list of files, or include a simple text file that contains a list of the files.
As an example, assume you created (or generated) a file named image-files.txt in which each line contains the base name of an image file, and embedded that file in your application:
List<String> imageNames;
try (BufferedReader linesReader = new BufferedReader(
new InputStreamReader(
Card.class.getResourceAsStream("image-files.txt"),
StandardCharsets.UTF_8));
Stream<String> lines = linesReader.lines()) {
imageNames = lines.collect(Collectors.toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
int random = rand.nextInt(imageNames.length());
String imageName = imageNames.get(random)));
BufferedImage img;
try {
img = ImageIO.read(Card.class.getResource(imageName));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return img;
Note: The getFile() method of URL does not return a valid filename. It only returns the path portion of a URL. There are many characters which would be illegal in URLs, so the path portion percent-escapes them. If you ignore this fact, the value returned by getFile() will eventually fail.
(The reason for the misleading method name is that the URL class was part of Java 1.0, and in the mid-1990s, all URLs actually referred to physical files.)
I need to use the File class
Each .jar entry is just a subsequence of compressed bytes within a single .jar file, so you will never be able to use File to read such an entry. Class.getResource and Class.getResourceAsStream are the only correct ways to read those entries.
The problem is that you are trying to access a URL of a resource as a file.
with this you can get all the images, and then you can do this:
List<String> arr = getResourceFiles("Images");
String imgPath = arr.get(rand.nextInt(arr.size()));
InputStream stream = Card.class.getResourceAsStream("Images/" + imgPath);
try {
img = ImageIO.read(stream);
} catch (IOException e) {
e.printStackTrace();
}
return img;
So we got this assignment in a basic java programming course and we're supposed to implement a kind of card deck. To help us with this they have given us resources that will present a GUI on the screen, but when running my program I get a IOException that says that it can't read the input file, most likely since the pathname is wrong. And I dont know how to fix it, we're not even supposed to be in meddling with this code. The error is thrown in this method:
private Image getImg(Card aCard) {
File pathToFile = null;
if (aCard == null) {
pathToFile = new File("cardset-oxymoron/shade.gif");
} else {
String suits = "cdhs";
char c = suits.charAt(aCard.getSuit());
String fileName = String.format("%s/%02d%c.gif", "cardset-oxymoron", aCard.getRank(), c);
pathToFile = new File(fileName);
}
Image img = null;
try {
img = ImageIO.read(pathToFile);
} catch (IOException ex) {
System.err.println("Failed to create image");
ex.printStackTrace();
}
return img;
}
And according to the error stack(?) it is at line 99, which is the
img = ImageIO.read(pathToFile);
line
The folder that the cards are in is inside the project folder, right in between bin and src. using IntelliJ debugger I can see that the the pathToFile is "cardset-oxymoron\02d.gif". The filename is correct as all the cards are "[01-13][c/d/h/s].gif". When I rightclicked and copied the path to the files inside IntelliJ it was using forwardsslashes and not backslashes. But then I checked in explorer and it was the other way around... I have no idea where this is going wrong, any input would be greatly appreciated!
According to your code your files are in directory cardset-oxymoron relative to your JVM run directory. I'm not sure about IntelliJ (I work all the time with Eclipse and Maven), but it could be bin directory.
You can check it by put those 2 lines to see what is it actually (somewhere before your actual code)
File currentDir = new File("./");
System.out.println(currentDir.getAbsolutePath());
Then your cardset-oxymoron must be in that directory. Or you can change file path appropriately.
E.g. if currentDir is bin then pathToFile will be
pathToFile = new File("../cardset-oxymoron/shade.gif");
as well as fileName for other case.
I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object.
I'm also not getting a NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a JAR and run in a terminal, but doesn't work when the JAR is double clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.
I had a similar problem once, which turned out to be down to issues relative addressing and my path being in the wrong place somehow. I dug this out of some old code I wrote that made it use an absolute path. That seemed to fix my problem; maybe it will work for you.
String basePath = (new File(".")).getAbsolutePath();
basePath = basePath.substring(0, basePath.length()-1);
FileConverter.loadImage(basePath+"/pictures/Logo1.png", this);
I am a new programmer to Java. I have a made a small Directory Application that I would like to export, but for some reason, whenever I try to export it to a runnable jar file, the result doesn't contain any of the images I specified within my program. Basically, I ran it in eclipse, and it worked fine, but when I ran it as an runnable JAR, it has no images. I have 5 .java files that are all bundled with eachother. My Images are found at Images/Image.png [I already made The Images folder a source folder.]
I have tried eveything, but for some reason i can't get it to work, if you have any knowledge on the topic, please tell me. I don't know if its because I'm a noob or something I'm doing wrong.
static ImageIcon logoicon = new ImageIcon("Images/Logo.png");
Here is the method I use:
public static ImageIcon createImageIcon(final String path) {
InputStream is = ImageLoader.class.getResourceAsStream(path);
int length;
try {
length = is.available();
byte[] data = new byte[length];
is.read(data);
is.close();
ImageIcon ii = new ImageIcon(data);
return ii;
} catch (IOException e) {
LogManager.logCriticalProblem("Image not found at {} - {}", new Object[]{path, e.getMessage()});
}
return null;
}
If you have problems with this method, try altering the path you're using:
"Images/Logo.png"
"/Images/Logo.png"
"src/Images/Logo.png"
"/src/Images/Logo.png"
Or other combinations depending on your package structure. For example, if your images are actually in net.blah.fizz.Images, your path would be "/net/blah/fizz/Images/image.png"
Did you try getResourceAsStream() method ? Checkout this page for more information
I'm trying to make the program to read QR codes, however when my code runs I am getting an exception javax.imageio.IIOException: Can't read input file. The image is in the src directory. Could someone please help me to find the problem in my code...
public class BarcodeSample {
public static void main(String[] args) {
Reader reader = new MultiFormatReader();
try {
BufferedImage image = ImageIO.read(new File("src/img.png"));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
BarcodeFormat format = result.getBarcodeFormat();
String text = result.getText();
ResultPoint[] points = result.getResultPoints();
for (int i=0; i < points.length; i++) {
System.out.println(" Point[" + i + "] = " + points[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
First, use File.separator instead of '/' as it places the right separator according to the OS it is running on.
Now the problem is with src/img.png. I suggest you put your images outside the src directory as this directory is used for code (not a must).
I do not know on which IDE you run it but make sure your workspace current directory is set to your project root directory so src/img.png will be found (assuming src is under you root current directory), otherwise you will get the file not found exception