NullPointerException while getting an Image - java

I am having trouble setting images in my newest game. When I call the method getImage(String), and I get the Image like so:
Image head = getImage("Torso_model_01.png");
I get the following error message:
Err: java.lang.NullPointerException
At PB2Main.Body(Body.java : 27)
...
and so on...
On this tutorial, it explains how to get an image using ImageIcon like so:
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
ImageIcon imageIcon;
Image image;
if(imgURL != null){
imageIcon = new imageIcon(imgURL);
image = imageIcon.getImage();
}
final Image anImage = image;
I made a method for this:
public URL getURL(String img){
String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
return imgURL;
}
Then I made a method called getImage(String)
public Image getImage(String img) {
ImageIcon imageIcon;
Image image;
URL imgURL = getClass().getClassLoader().getResource(getURL(img));
if(imgURL != null){
imageIcon = new ImageIcon(imgURL);
image = imageIcon.getImage();
return image;
}
System.err.println("Unable to Locate Image: " + imgURL);
}
Now, I have a class called Body.
In that class, I have a constructor:
public Body(float x, float y, String head, String torso){//atm this is just so i can get the image to actually draw on the screen
Image Head = debugger.getImage(head);// debugger doubles as a library and debugger
//i also can't have this class extend debugger otherwise it will create a window :/
// is that a glitch or something in Java? :L perhaps i just don't understand
// inheritance very well and what happens exactly when you inherit a class :(
Image Torso = debugger.getImage(torso);
g2.drawImage(Head, canvas.geWidth()/ 2,canvas.getHeight()/2, null)// canvas: the window to
//draw to
// can someone also quickly explain in their answer what an image observer is please?
g2.drawImage(Torso, Head.getX() - 5, Head.getY() - 5, null);
}
The compiler gives me the following error message:
java.lang.NullPointerException
At PlazmaBurst2.Body(Body.java: 37)
//the code it brings me to is line 1 in the constructor:
/* null: */ Image Head = debugger.getImage(img);
I don't understand where this NullPointerException is coming from. I did it exactly how they do it in the Custom Graphics Programming section of the same site.
The code works fine if I just copy and paste the code, but not if I use the method getImage(String).

You're problem is on line 3 of getImage(String):
URL imgURL = getClass().getClassLoader().getResource(getURL(img));
This should be changed to:
URL imgURL = getURL(img);

Related

byte [] or Bitmap to ImageProxy/Image

I'm implementing a frame processor plugin (react-native-vision-camera). I would like to be able to load an image from a file and return it instead of the ImageProxy type frame so I can controll frames content.
For that, I have to load an image (no worries so far) and create an Image or an ImageProxy from the loaded image.
(I also tried to replace the bytes of the ImageProxy type image with those of the loaded image but I didn't succeed either. So I am also interested in this topic.)
#Override
public Object callback(#NotNull ImageProxy image, #NotNull Object[] params) {
try {
// Get path of image to load
String param = params[0].toString();
Bitmap bmImg = BitmapFactory.decodeFile(param);
ImageView img = new ImageView(this);
img.setImageBitmap(bmImg);
return img;
//return image;
} catch (Exception e) {
System.out.println("CRASHED");
e.printStackTrace();
}
return null;
}
To do this I tried the code above but I am creating an ImageView and not an Image or an ImageProxy.
Any idea or sample code so I can control frame content?
Thanks in advance

Java Constructor with ImageIcon

I created a small program that inserts an ImageIcon (resized in another class) into a JLabel through a constructor
I am struggling to return the icon in the JLabel
Here's my code:
Main Class:
traforma imageObj = new traforma("image1.png"); //traforma is another class
ImageIcon Icon11 = new ImageIcon(imageObj.Icon11);
imageLabel.setIcon(Icon11); //Here he gives me error, he can't find my ' Icon11 '
traforma Class:
public class traforma {
public traforma(String image) {
ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
Image image = Icon1.getImage();
Image newimg = image.getScaledInstance(470, 360, java.awt.Image.SCALE_SMOOTH);
ImageIcon Icon11 = new ImageIcon(newimg);
}
Object Icon11 = this.Icon11; // i guess the problem is here
}
I am new to Java,
Hope I have been clear
This code makes no sense:
Object Icon11 = this.Icon11;
The problem is, that the variable "Icon11" that you initialized within the method is not used anywhere. After method completed, it will be thrown away. What you can do, is to assign the created icon object to the member variable, not to the local variable.
Thy style of your code is not perfect: the usage of lower and upper case, the usage of ImageIcon instead of directly loading image, etc. But if we keep it as close to your code as possible and try to do minimal changes, the working code may look as follows:
public class traforma {
public traforma(String image) {
ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
Image image = Icon1.getImage();
Image newimg = image.getScaledInstance(470, 360, java.awt.Image.SCALE_SMOOTH);
this.Icon11 = new ImageIcon(newimg);
}
public ImageIcon Icon11;
}

Java Applet Image Load

I want to display an image icon in my applet.I created a package resources and saved my image in it.This is what i tried :-
Image logo;//I declare globally
logo = getImage("logo.jpg");//I initialize in the constructor
And i use this proceedure
public Image getImage(String name){
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
return icon.getImage();
}
public void paint(Graphics g)
{
if (logo!=null){
g.drawImage(logo, 30, 30, null);
}
g.drawString("Hwllo", 12, 12);
}
Then i call the:
repaint() //In the Constructor
But i dont see an image or my String.What might be the problem.Moreover is there any easier method to load images in the Applet??
You setting the URL to the
URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
ImageIcon icon = new ImageIcon(imgUrl);
But while Calling paint method, you are calling the logo variable
g.drawImage(logo, 30, 30, this);
The problem is in your setting URL value, set URL to your logo variable like
URL url = new URL(/*Your resources herre*/, /*Your file name here*/);
logo=getImage(url);
After that display image using paint method.

I want to simplify things in my Java program

I made a game using NetBeans design tool, called WordHunt. It looks like this:
I need to make a class that will apply a mouseover effect to those 16 labels I have. This is the code that changes the icon B when enter the mouse:
private void b1MouseEntered(java.awt.event.MouseEvent evt) {
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
}
I had applied a default icon to the label.
After making that class, instead of writing:
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
to write className(b1 ,B);
For the next label, the same thing
className(b2 ,C);
Observation: b1 is a label and I have all letters icon in .png format from A to Z.
Can anybody give me an idea of how I can do that?
If I understand what you want to do, you can use this method:
public void setRolloverIcon(Icon rolloverIcon)
defined in the class JButton to configure the rollover icon.
Just create a simple class like this:
class HoverEffectButton extends JButton{
HoverEffectButton(Image img1, Image img2) {
super(new ImageIcon(img1));
this.setRolloverIcon(new ImageIcon(img2));
}
}
Hope this will help.
And of course you can create a helper class that permits to load an image according to the image name
class AssetsHelper{
private static final String DEFAULT_ASSETS_ROOT = "assets/";
private static final String DEFAULT_IMAGE_SUBFIX = ".png";
public static Image loadImage(String name){
BufferedImage img = null;
try {
img = ImageIO.read(new File(DEFAULT_ASSETS_ROOT + name + DEFAULT_IMAGE_SUBFIX));
} catch (IOException e) {
....
}
return img;
}
}
How about something like this: (rough draft)
// for storage so we don't load it for each mouse-over
HashMap<String, ImageIcon> images = new HashMap<String, ImageIcon>();
void setIcon(JLabel button, String image)
{
if (images.containsKey(image))
return images.get(image);
else
{
String path = "/ip/imag/" + image + ".png";
ImageIcon icon = new ImageIcon(getClass().getResource(path));
images.put(image, icon);
return icon;
}
}
And then:
setIcon(b1, "B");
But you should probably consider using buttons so you can use setRolloverIcon rather than MouseEntered.
public class MyButton extends JButton {
private ImageIcon normalIcon;
private ImageIcon hoverIcon;
public MyButton(String normalURL) {
String hoverURL = normalURL.replaceFirst("\\.png$", "-hover.png");
normalIcon = new ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png"); // or so
hoverICon = ...
}
private void b1MouseEntered(MouseEvent evt) {
setIcon(hoverIcon);
}
}
Firstly at the top of your code add this import:
import javax.swing.ImageIcon;
//Then you only need to write
new ImageIcon(...);
Instead of:
new javax.swing.ImageIcon(...)
Already shorter :)
Then you can create a hashmap of the images preloaded where each instance of B is the key and the loaded icon is the value.
if i get u well i think you want just an image and not evry image to chang when mouse is on it right. if that is the case what u should do is to get the position of each image in a buffer and compare it with the mouse x n y position to know wc image to change. I hope this solve your problem

Error loading image to set background

I am trying to load an image and set to background, but i get the error at selectionPanel method "Could not load background image".
It seems that something is going wrong with the image processing but i cant find out what.
public class selectionPanel extends JPanel
{
//Variable with the name of our pic
private static final String path = "selbkgrnd.jpg";
private ImageIcon imageIcon;
private Dimension windowSize;
private int imageHeight;
private int imageWidth;
protected selectionPanel()
{
this.imageIcon = new ImageIcon("selbkgrnd.jpg"); //Save image to imageIcon
Image image = this.imageIcon.getImage();
this.imageWidth = image.getWidth(null);
this.imageHeight = image.getHeight(null);
if ((this.imageWidth == -1) || (this.imageHeight == -1)) //Check if background image is succesfully loaded
{
JOptionPane.showMessageDialog(JOptionPane.getDesktopPaneForComponent(this), "Could not load background image", "Fatal error!", 0);
System.exit(-1);
}
this.windowSize = new Dimension(this.imageWidth, this.imageHeight);
}
protected void startScreen()
{
setOpaque(false);
setSize(this.windowSize);
}
protected int getImageHeight()
{
return imageHeight;
}
protected int getImageWidth()
{
return imageWidth;
}
#Override
public void paintComponent(Graphics g)
{
g.drawImage(this.imageIcon.getImage(), 0, 0, null);
super.paintComponent(g);
}
}
Usually this is due to your looking in the wrong location for your Image File. Try using the complete path to the image, either that or a path relative to the user's directory which can be found with:
System.out.println("user directory: " + System.getProperty("user.dir"));
Edit
You state:
Thank you it worked with the full path, but isnt it supposed to work with just the image name if it is inside the source code folder ?
No. Again, Java will look for the file relative to the user directory.
Note however that if the image is in the class file directory or in a directory relative to this and you make a jar file out of this and need to access the images, then you can't use files. You will need to get the images as a resource and the relative path will be different since it won't be related to the user.dir but rather will be relative to the location of the class files.

Categories

Resources