Java in netbeans, read image file from java package - java

I wonder if anyone could help? I have been developing a java app which displays images from disk on a jframe.
Using netbeans I have created a java package called images within my project and stored the images in that package. First off is that the way I should do it If I want them to ship with the app?
I have the following function to read the image:
Image readImg(String file)
{
Image image = null;
try {
File imgFile = new File(file);
image = ImageIO.read(imgFile);
} catch (IOException e) {
// System.out.println("Can not Display Image");
e.printStackTrace();
}
if (image != null){
return image;
} else{
return null;
}
}
My problem comes that I cannot work out the relative filepath to pass to the function. I have got the image to display calling it like so:
Image headerImg = readImg("C:\\Users\\D#nb0y\\Documents\\NetBeansProjects\\GiftAidApp\\src\\images\\galogo.png");
Obviously this will completely fall apart if the app is run on any other device. Can anyone give me a heads up as to making this code portable?
thanks very much

Since it's a JFrame you're trying to add an image to, it might be better to use an ImageIcon instead of an Image.
Try this:
ImageIcon image = new ImageIcon("images/galogo.png");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
This should make the app portable as well if you include you images folder along with your project.

Related

How to set a standard image to show if a search for associated image name yields no results?

I am working on a project for my course and have been asked to show an associated image for products in a system, the user can add products, and he enters the name of the image file whilst doing so. the program then finds the image file and displays it with the product information.
I would like to add some additional code so that if there is no image file matching the string input that a standard image is shown. The code I have so far either shows the image file if it is found or does not show anything. can someone show me how to modify it so that it can show a standard image if no associated image file is found. the standard image is simply "no-image-found.jpg". Here is the code:
public void showImage(JLabel imageArea, String image){
BufferedImage img = null;
try {
img = (BufferedImage)ImageIO.read(new File(image));
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
any help is very much appreciated, and my sincere apologies if this is a noob question, I am quite new to java.
In the catch, you could load the standard image and show it
Basically check for image existence assuming path is valid otherwise get the standard image. You can have something similar:
public void showImage(JLabel imageArea, String image)
{
BufferedImage img = null;
try
{
file = new File(image);
if (file.exists())
{
img = ImageIO.read(file);
}
else
{
file = new File(standardImagePath);
img = ImageIO.read(file);
}
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}

Load images in jar file

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);

Jar Exportation Not Showing Images

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

Load and display all the images from a folder

I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}

ImageIcon not displayed after creating jar

i'm trying to make a small project in java with no luck
if i'm compiling the program with eclipse everything is good, but when i'm i creating the jar file i get a blank window
this is the image i declared for:
public ImageIcon BACKGROUND = new ImageIcon() ;
I have tried to do the following stuff:
1.
new ImageIcon("Images/wood.jpg").getImage());
2.
this.BACKGROUND.setImage(Toolkit.getDefaultToolkit().getImage("Images/wood.jpg"));
3.
this.BACKGROUND = new ImageIcon(getClass().getResource("Images/wood.jpg"));
4.
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
1 & 2 showing the images after compiling and 3 & 4 returns null
another think is that i'm using mac and when i'm working with windows no image is displayed after compiling.
Here's a small working example if that helps:
public class ImageIconApplet extends JApplet {
public void init() {
URL url = getClass().getResource("/images/WhiteFang34.jpg");
ImageIcon icon = new ImageIcon(url);
JLabel label = new JLabel(icon, JLabel.CENTER);
add(label);
}
}
The jar for the applet on that page contains two files:
/com/whitefang34/ImageIconApplet.class
/images/WhiteFang34.jpg
I'm not sure if you're deploying an applet or a desktop swing app, however the code to load images and the packaging requirements are the same either way.
I have something...
ImageIcon icon = new ImageIcon(getClass().getResource("/package/image.png"));
JFrame.setIconImage(icon.getImage());
Place this inside your constructor.
Are you sure Images/wood.jpg is present in the .jar file?
I suggest you unzip the jar file and make sure that it's there. Otherwise you'll have to revise your build scripts (or what ever technique you use) that builds the jar.
Related questions:
adding non-code resources to jar file using Ant
Add image to JAR Java

Categories

Resources