I'm getting an error that I don't understand. It's a Null Pointer Exception, but neither of my arguments in line 118 is null. According to the documentation, ImageIO.write will throw a IllegalArgumentException or an IOException, but it isn't throwing either. I'm not sure what could be null here. You can run the program, then press the "Create New Image" button, then the "Save Image To File" button to get the error. Here is the code. The exception is caught on line 132. Lines 115 and 117 don't display. Lines 120 - 129 do not execute. Any ideas on what could cause the exception? Thanks.

package ColorForms;

import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import java.util.*;
import javax.imageio.ImageIO;



public class ColorForms extends JFrame
{
    LeftPanel leftPanel;
    TopPanel topPanel;
    CanvasPanel canvasPanel;
    JSplitPane wholePanel, bottomPanel;
    
    public static void main (String args[])
    {
        ColorForms cf = new ColorForms ();
    }
    
    
    public ColorForms ()
    {
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        this.setSize (400, 400);
        
        leftPanel = new LeftPanel ();
        canvasPanel = new CanvasPanel ();
        topPanel = new TopPanel (canvasPanel);
        
        bottomPanel = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvasPanel);
        bottomPanel.setDividerLocation (50);
        wholePanel = new JSplitPane (JSplitPane.VERTICAL_SPLIT, topPanel, bottomPanel);
        wholePanel.setDividerLocation (70);

        this.getContentPane ().add (wholePanel);
        this.setVisible (true);
        canvasPanel.repaint ();
    }
}


class LeftPanel extends JPanel
{
    public LeftPanel ()
    {        
    }
}


class TopPanel extends JPanel implements ActionListener
{
    JButton createNewImageButton;
    JButton saveImageToFileButton;
    JButton retrieveImageFromFileButton;
    CanvasPanel cp;
    
    public TopPanel (CanvasPanel canPan)
    {
        cp = canPan;
        createNewImageButton = new JButton ("Create New Image");
        saveImageToFileButton = new JButton ("Save Image To File");
        retrieveImageFromFileButton = new JButton ("Retrieve Image From File");
        this.add (createNewImageButton);
        this.add (saveImageToFileButton);
        this.add (retrieveImageFromFileButton);
        createNewImageButton.addActionListener(this);
        saveImageToFileButton.addActionListener(this);
        retrieveImageFromFileButton.addActionListener(this);
    }

    
    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource () == createNewImageButton)
            CreateNewImage ();
        else if (e.getSource () == saveImageToFileButton)
            SaveImageToFile();
        else if (e.getSource () == retrieveImageFromFileButton)
            RetrieveImageFromFile ();
        
        cp.repaint ();
    }
    
    
    public void CreateNewImage ()
    {
        cp.bi = new BufferedImage (200, 200, BufferedImage.TYPE_INT_ARGB_PRE);
        Color color1 = new Color(0, 0, 255, 255);
        Color color2 = new Color(255, 0, 0, 100);
        int rgb1 = color1.getRGB();
        int rgb2 = color2.getRGB();
        for (int i = 0; i < 50; i++)
        {
            for (int j = 0; j < 50; j++)
            {
                cp.bi.setRGB(i, j, rgb2);
            }
        }        
    }
    
    
    public void SaveImageToFile ()
    {
        try
        {
             File saveFile = new File("SemiTransparentSquare.gif");
             if (saveFile == null)
                 System.out.println ("saveFile is null");
             if (cp.bi == null)
                 System.out.println ("cp.bi is null");
             ImageIO.write(cp.bi, "gif", saveFile);           
        }
        catch (IllegalArgumentException ex)
        {
            System.out.print ("Caught an illegal argument exception - ");
            System.out.println (ex.toString());            
        }
        catch (IOException ex)
        {
            System.out.print ("Caught an IO exception - ");
            System.out.println (ex.toString());            
        }
        catch (NullPointerException ex)
        {
            System.out.print ("Caught a null pointer exception - ");
            System.out.println (ex.toString());            
        }
        catch (Exception ex)
        {
            System.out.print ("Caught an exception - ");
            System.out.println (ex.toString());
        }
    }
    
    
    public void RetrieveImageFromFile ()
    {
        try 
        {
            File biFile = new File("SemiTransparentSquare.gif");
            cp.bi = ImageIO.read(biFile);
        } 
        catch (IOException ex) 
        {
            System.out.println ("Problem opening file");
        }        
    }
}


class CanvasPanel extends JPanel
{
    BufferedImage bi;
    
    
    public CanvasPanel ()
    {
    }


    public void paintComponent (Graphics g)
    {
        super.paintComponent (g);        
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.GREEN);
        g2.setColor(Color.WHITE);
        g2.fillOval (50, 50, 75, 75);
        g2.drawImage (bi, 50, 50, null);
    }
}

if (cp.bi == null) What if cp is null ?

Try to print everything before you run anything:

File saveFile = new File("SemiTransparentSquare.gif");

System.out.println("saveFile: "+saveFile);

if (saveFile == null)
System.out.println ("saveFile is null");

System.out.println("cp: "+cp);
System.out.println("cp.bi: "+cp.bi);

if (cp.bi == null)
System.out.println ("cp.bi is null");
ImageIO.write(cp.bi, "gif", saveFile);

if (cp.bi == null) What if cp is null ?

Try to print everything before you run anything:

File saveFile = new File("SemiTransparentSquare.gif");

System.out.println("saveFile: "+saveFile);

if (saveFile == null)
System.out.println ("saveFile is null");

System.out.println("cp: "+cp);
System.out.println("cp.bi: "+cp.bi);

if (cp.bi == null)
System.out.println ("cp.bi is null");
ImageIO.write(cp.bi, "gif", saveFile);

That's debugging code. cp.bi shouldn't be null (I should actually have it return from the function if it is). I added those lines in to demonstrate that they don't display, yet I still get a null pointer exception even though neither cp.bi is null, nor is saveFile null. So what could be null?

Give me a minute to run the code

Well for starters it always helps when debugging to add a ex.printStackTrace() in the catch:

System.out.print ("Caught a null pointer exception - ");
            System.out.println (ex.toString());   
            ex.printStackTrace();

After doing so, I noticed that none of your aruments is null. This is what I got:

java.lang.NullPointerException
at com.sun.imageio.plugins.common.PaletteBuilder.findPaletteEntry(PaletteBuilder.java:310)
at com.sun.imageio.plugins.common.PaletteBuilder.getIndexColorModel(PaletteBuilder.java:296)
at com.sun.imageio.plugins.common.PaletteBuilder.getIndexedImage(PaletteBuilder.java:145)
at com.sun.imageio.plugins.common.PaletteBuilder.createIndexedImage(PaletteBuilder.java:77)
at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:564)
at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:492)
at javax.imageio.ImageWriter.write(ImageWriter.java:598)
at javax.imageio.ImageIO.write(ImageIO.java:1479)
at javax.imageio.ImageIO.write(ImageIO.java:1521)

at ColorForms.TopPanel.SaveImageToFile(TopPanel.java:87)
at ColorForms.TopPanel.actionPerformed(TopPanel.java:46)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

I have never used these classes before so I am not sure how they need to be instantiated. I believe that maybe when the java methods are called
(from the stack trace:
at javax.imageio.ImageWriter.write(ImageWriter.java:598)
at javax.imageio.ImageIO.write(ImageIO.java:1479)
at javax.imageio.ImageIO.write(ImageIO.java:1521)
)
something that was not supposed to be is null when they use your arguments. I cannot say much so you would better wait for someone better to see this and figure it out

Sorry

Null pointer exceptions are unchecked (the documentation will never say that a method can throw it). So it could be thrown from one of the methods you call.

Can you add ex.printStackTrace() to the section of code where you check the NullPointerException and then run the program again? That should help figure out what's going on.

EDIT: what javaAddict said

It may be possible that Java won't support an image-type in future releases and therefore not provide Serialization support for it but that depends on what it is.

I remember getting warning pertaining to images of a specific class and that class might be the culprit but I can't completely confirm this @_@. It's just a possibility >_<

-Alex

Try saving it to a .png instead of a .gif, that should (hopefully) work.

commented: I would have never thought of that +3

Try saving it to a .png instead of a .gif, that should (hopefully) work.

I changed in the code this: ImageIO.write(cp.bi, "gif", saveFile); into this: ImageIO.write(cp.bi, "png", saveFile); or ImageIO.write(cp.bi, "jpeg", saveFile); And it worked. Although the file saved in my file system has extension .gif ??

> And it worked. Although the file saved in my file system has extension .gif ??

The file name doesn't matter; its content does. I could have very well named it 'image.exe' and it still wouldn't have mattered. Maybe you overlooked the declaration File saveFile = new File("SemiTransparentSquare.gif"); in which the file name is pretty much a constant.

> And it worked. Although the file saved in my file system has extension .gif ??

The file name doesn't matter; its content does. I could have very well named it 'image.exe' and it still wouldn't have mattered. Maybe you overlooked the declaration File saveFile = new File("SemiTransparentSquare.gif"); in which the file name is pretty much a constant.

Oops

PNG worked for me too. I'm hoping to use gifs because I need an animation option and my understanding is that you can't do that with PNG files. I was able to save a JPanel as a GIF, but the transparency was lost and I am trying to maintain that alpha transparency. Saving the JPanel as a GIF contained more code and it worked, but this was an attempt to save an image directly as a GIF. I'll play around and post another attempt. Thanks to all who have responded so far!

OK, I'm marking this one solved. I'm just going to use png instead of gif for now and worry about the animation later. I have another issue, but I'm going to start a new thread for it. Thanks everyone!

I am too having the same issue as mentioned in this thread i.e. NullPointerException.
In my case in the call to ImageIO.write(image, "png", fileOutput), the output file path is non-existent. I gave a non-existent path to test something but I am getting NullPointerException.. Don't know why?

I get it for jpg, png type of file also. Can anyone help with this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.