Accessing Images from image folder in JAVA - java

I'm beginner to java GUI. And want to access images from the folder but i'm getting the following error.
My Code
import java.awt.Image;
import javax.swing.ImageIcon;
public class Images {
private static String IMG_FOLDER = "C:/Users/RASHID/workspace/images/";
public static Image ICON = getImage(IMG_FOLDER + "icon.png");
private static Images instance;
private Images() {}
public static Images getInstance() {
if(instance==null)
instance = new Images();
return instance;
}
public static Image getImage(String image){
return getImageIcon(image).getImage();
}
public static ImageIcon getImageIcon(String image){
return new ImageIcon(getInstance().getClass().getClassLoader().getResource(image));
}
}
When i try to run this one in main i get the following Errors. I don't know whats happening here.
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Images.getImageIcon(Images.java:38)
at Images.getImage(Images.java:34)
at Images.<clinit>(Images.java:9)

You don't use classloaders to fetch files from hard drive. Instead, you need to fetch them as Files and transform to Images first:
File sourceimage = new File("c:\\mypic.jpg");
Image image = ImageIO.read(sourceimage);
return new ImageIcon(image);
(taken directly from this site - take a look)

You are trying to construct ImageIcon object using a constroctur that takes URL paramter (because getResource() method returns URL object, and by the way in this case it returns null, hence NullPointerException)
You should use ImageIcon(String filename) constructor instead, which will create ImageIcon from the file specified.

Read from Local Folder
File sourceimage = new File("c:\\picture_name.jpeg");
Image image = ImageIO.read(sourceimage);

Related

Java Class decorate itself

I think I kind of reinvent caching in Java but have a point I don't get further.
In case the answer is anywhere on Stackoverflow for this issue I might had not understood it when searching or didn't understand the required complexity and searched for a more easy way.
Short what I want to do: call a method on an Object. The object should load a picture and store it as Image. Then it should decorate itself with an Decorator so that called method will next time only return the image with no more IO operations.
My Interace Picture Interafce is simple like this:
import java.awt.*;
public interface PictureInterface {
public Image getImage();
}
My Decorator looks like this:
import java.awt.*;
public class PictureDecorator implements PictureInterface {
private final Picture p;
public PictureDecorator(Picture p){
this.p = p;
}
public Image getImage(){
return this.p.pipeImage();
}
}
It saves a Picture and on getImage() calls pictures pipeImage - the picture "real" getImage().
And last but not least the Picture Class:
import java.awt.Image;
public class Picture implements PictureInterface{
private final String path;
private final Image image;
public Picture(String path){
this.path = path;
}
private void loadImage(){
this.image = /*IO Magic Loading the Image from path*/
}
public Image getImage() {
loadImage();
/*Decorate Yourself with Picture Decorator*/
return /*Decorator.getImage*/;
}
Image pipeImage(){
return this.image;
}
}
If getImage is called I want Picture to Decorate itself and call the Decorators getImage and most importent overwrite its old refference (Java is call by value, this is where i'm stuck atm) so on further getImage Calls the Decorators getImage Method is called.
As a little extra-question I think my access to the mage from Decorator is not best practice, hints welcome ^^
EDIT:
To add a thing: I allready thought if this it not possible: what would be "smarter": go for if(image==NUll) or make a decorateYourself() function where image is loaded and decorator returned in Picture and in Decorator it only returns itself, apply this to the Image var and then call getImage, like:
ImageInterface x = new Image("path);
x = x.decorateYourself()
Image i = x.getImage()
this ways i would only do a method-call to return the decorator itself, but i have to call both methods ...
If getImage is called i want Picture to Decorate itself and call the
Decorators getImage and most importent overwrite its old refference
(Java is call by value, this is where i'm stuck atm) so on further
getImage Calls the Decorators getImage Method is called.
A decorator doesn't work in this way.
With decorator you want to augment or diminish a behavior of an existing class without being invasive for this class : no needed modification.
So the decorator instance decorates an object that has to share with the decorator class a common type and a common method.
Besides I don't think that you need to use a decorator.
Here you don't decorate a picture but you bypass its loading if it was already previously performed.
I think that it would be more suitable to use a proxy that decides whether it must load the resources of get it from the cache.
Don't worry, it doesn't change many things in the classes you have introduced: interface, common method and object wrapping are still required.
In your case PictureInterface is the common type between the proxy class and the proxy subjects classes that provides the common method : getImage().
import java.awt.*;
public interface PictureInterface {
public Image getImage();
}
PictureProxy, a proxy class could implement PictureInterface to act as any PictureInterface instances.
PictureProxy should be responsible to check if it has cached the result of a previous loading of the image. It is the case it returns it. Otherwise it calls getImage() on the Picture instance that holds and it caches the result.
import java.awt.*;
public class PictureProxy implements PictureInterface {
private final Picture p;
private final Image image;
public PictureProxy(Picture p){
this.p = p;
}
public Image getImage(){
if (image != null){
return image;
}
image = p.getImage();
return image;
}
}
And Picture class should not be aware of the proxy when it performs getImage().
It is the proxy class that handles the state of the cache.
import java.awt.Image;
public class Picture implements PictureInterface{
private final String path;
private final Image image;
public Picture(String path){
this.path = path;
}
private void loadImage(){
this.image = /*IO Magic Loading the Image from path*/
}
public Image getImage() {
loadImage();
return image;
}
}
From the client of the classes you could do something like that :
Picture picture = new PictureProxy(new Picture("picturePath"));
Image img = picture.getImage(); // load the image from Picture the first time and get it
Image img = picture.getImage(); // get it from the PictureProxy cache

How to replace default image when user selected image?

I have one default image and I want to replace the image when the user or the program already selected an image. I have only the basic image reader for displaying the default image.
private static void loadImage()throws Exception{
File image2 = new File("...Example\\blackimage.jpg");
bi = ImageIO.read(image2);
}
You could override methods so
private static void loadImage(String imagePath) throws Exception {
File image2 = new File(imagePath);
bi = ImageIO.read(image2);
}
private static void loadImage() throws Exception {
loadImage("...Example\\blackimage.jpg");
}
This would give you two methods, one to call if you have a image in mind and one for the default image.
If your program already has one selected for a particular user, for example stored in some sort of local storage / database, it can call the first method, however if an image is not found it can call the default no parameter method.

Image from relative package

I'm making a simple game using the java applet. I want to add buffered images to the project.
I've created a package called "resources.images.sprites" and I've put images in there.
How can I access the images?
I've tried using relative paths, but "." starts outside of the bin, so if I were to put the game on a website, I wouldn't be able to access it.
Any ideas?
Here's the main code I'm using for testing...
package resources;
import java.io.File;
import java.util.HashMap;
import entities.Sprite;
public class ImageLibrary {
private static final File sprite_path = new File(".");
private static File[] sprite_files = sprite_path.listFiles();
//private static HashMap<String,Sprite> sprite_map = new HashMap<String,Sprite>();
public static void main(String[] args){
System.out.println(sprite_files[0]); // To check the folder it's in...
}
}
Edit:
I took the accept answer, and then realized I could use the getPath method on the URL object to get what I wanted to achieve.
Use a ClassLoader.
Classloader cl = ImageLibrary.class.getClassLoader();
URL imageUrl = cl.getResource("resources/images/sprites/MyImage.png");
Once you have a URL for the image you can turn that in to an InputStream if you need to.
InputStream imageStream = imageUrl.openStream();

Java: When a program is .jar 'ed, it no longer reads the images in the jar file?

I need it to run without having the files exported to the computer.
At the moment, my code for storing the images is:
ImageIcon icon = new ImageIcon("images\\images2.gif");
It can't just be an image since I'm adding it to a JLabel.
When I jar the entire program, it stores the image files in the jar.
When I go to run the actual problem, there are no images.
Again, I can't just leave the .jar in a folder with the images already. It has to work on a separate computer, by itself.
You'll want to get the image via the system class loader:
URL url = ClassLoader.getSystemClassLoader().getResource("images/images2.gif");
Icon icon = new ImageIcon(url)
images is at the root of the classpath.
Note that the Java runtime will translate the separator (/) to the OS specific separator (\ for Windows).
You need to access those files through class-loader... Something like this:
InputStream is = this.getClass().getClassloader().getResourceAsStream("images/image.ico");
HTH
UPD: note, that this will work both with JARed package and with plain directory structure.
The basic issue is that the File class only knows how to work with what the underlying operating system consider a file, and a whole one.
A jar file is essentially a zip file with some extra information so you cannot use File's with that. Instead Java provides the "resource" concept which roughly translates to "a chunk of bytes or characters which we don't care where is, as long as we have them when we need them". You can ask the class loader for any resource in the class path - which is what you want here - or access it through an URL.
Try this:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("images/images2.gif"));
if that doesn't work, replace this.getClass().getClassloader() with MyClass.class where MyClass is the name of your class.
I remember having to edit this slightly to make it work in Eclipse, but when you deploy it, it works like a charm.
Edit: To make it work in Eclipse, you may need to change it to:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("bin/images/images2.gif"));
If that doesn't work, do the standard, replace this.getClass().getClassloader() with MyClass.class. If it still doesn't work, try replacing "bin" with "src". Try jar'ing it with the first way and see what happens.
Here is a convenient utility class that can be used for loading image resources. The log4j logger can be removed of changed to whatever is more appropriate.
public class ResourceLoader {
private static final Logger logger = Logger.getLogger(ResourceLoader.class);
public static Image getImage(final String pathAndFileName) {
try {
return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static ImageIcon getIcon(final String pathAndFileName) {
try {
return new ImageIcon(getImage(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
}
I suppose images2.gif is inside the package images
URL imageurl = getClass().getResource("/images/images2.gif");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
piclabel.setBounds(0,0,myPicture.getWidth(null),myPicture.getHeight(null));
If your images are located this way.
Then this should do the job.
private String imageLocation "/images/images2.png";
private ImageIcon getImageIconFromJar(String imageLocation)
{
try
{
BufferedImage bi = ImageIO.read(this.getClass().getResource(imageLocation));
ImageIcon ic = new ImageIcon(bi);
return ic;
} catch (IOException e)
{
System.out.println("Error: "+e);
}
return null;
}

Loading image in Java J2ME

I have a problem with loading image with java 2ME. I have a image file "picture.png" in location drive "C:". After that I wrote my like this to show image from this location.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class ImageMidlet extends MIDlet implements CommandListener{
private Display display;
private Command exitCommand;
private Command backCommand;
private Command okCommand;
private Form form;
private ImageItem imageItem;
private Image image;
public ImageMidlet(){
display = Display.getDisplay(this);
form=new Form("");
exitCommand = new Command("Exit", Command.EXIT, 1);
backCommand = new Command("Back", Command.BACK, 2);
okCommand = new Command("OK", Command.OK, 3);
try {
image=Image.createImage("/picture.png");
imageItem=new ImageItem(null,image,ImageItem.LAYOUT_NEWLINE_BEFORE,"");
}
catch(IOException ex){
}
form.append(imageItem);
form.addCommand(okCommand);
form.addCommand(exitCommand);
form.addCommand(backCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c,Displayable d){
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
It shows me this error:
Unable to create MIDlet Test.ImageMidlet
java.lang.NullPointerException
at javax.microedition.lcdui.Form.append(Form.java:638)
at Test.ImageMidlet.<init>(ImageMidlet.java:39)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
at com.sun.midp.midlet.Selector.run(Selector.java:151)
I am starting learn to develop, so please guide to do this.
Image.createImage(String name) loads the given image as a resource. Resources are loaded with Class.getResourceAsStream(name), which looks up the resources from classpath, not from your file system root.
You should put the image file in your classpath, which is usually the final application .jar file. Usually a folder called resources or res is created under the project, where the images are placed. The contents of this folder are then copied to the .jar file. In development phase you should be able to append your resource folder to the classpath with a command-line parameter (java -cp resources in Java SE) or with a similar IDE setting.
If you are really interested in loading the images from actual file system, you can use optional FileConnection API (http://developers.sun.com/mobility/apis/articles/fileconnection/). The handset support for this API is limited though. For static images the classpath is the way to go.
As msell said - You can't access images from Your computer. Make sure that You have included the given image in midlet jar file. If You try to access it using '/picture.png', then it should be located a the root directory in jar.
First of all place your image in default package.
I have placed "My Network Places.png" in default package.
Then create MIDlet named "ImageItemExample"
then copy below code in that MIDlet file.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ImageItemExample extends MIDlet implements CommandListener{
private Display display;
private Command exit;
private Form form;
private ImageItem logo;
public ImageItemExample(){
form = new Form("Image Item");
exit = new Command("Exit", Command.EXIT, 0);
try{
logo = new ImageItem(null, Image.createImage("/My Network Places.png"),
ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_NEWLINE_AFTER, "Roseindia");
form.append(logo);
}catch(IOException e){
form.append(new StringItem(null, "Roseindia: Image not available: "+ e));
}
}
public void startApp(){
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable d){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(true);
}
}
}
My guess is that
image=Image.createImage("/picture.png");
throws an exception which prevents the creation of a new object of type ImageItem which leaves your imageItem variable as null. This gives you the null pointer exception.
Isn't your file Picture.png and not Pictur.png?
Verify that the file picture.png actually exists
depending on the device emulator/IDE there should be a way to set the "HOME" directory for the device. In your case, this would be "C:\"

Categories