Amir Sasani
Amir Sasani

Reputation: 327

Trouble with jar file and image

I have coded a program in Eclipse and it works properly when I run in that.

public static void initialize() throws IOException{     

    JTextField tfQrText;
    int size = 250;
    File qrFile;
    BufferedImage qrBufferedImage;

    JFrame gui = new JFrame("qrCode Generator");
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setSize(250, 340);
    gui.setLayout(new BorderLayout());
    gui.setResizable(false);


    File iconFile = new File(VisualQrCodeGenerator.class.getResource("icon.png").getFile());    
    BufferedImage iconBuffered = ImageIO.read(iconFile);
    gui.setIconImage(iconBuffered);

    JButton generate = new JButton("Generate qrCode");
    gui.add(generate,BorderLayout.SOUTH);

    tfQrText = new JTextField();
    PromptSupport.setPrompt("Enter Your Text ... ", tfQrText);
    gui.add(tfQrText,BorderLayout.NORTH);


    qrFile = new File(VisualQrCodeGenerator.class.getResource("qrCodeImage.png").getFile());
    qrBufferedImage = ImageIO.read(qrFile);
    ImageIcon qrImageIcon = new ImageIcon(qrBufferedImage);

    JLabel image = new JLabel();
    image.setIcon(qrImageIcon);

    image.setHorizontalAlignment(JLabel.CENTER);

    gui.add(image,BorderLayout.CENTER);

    gui.setVisible(true);
    generate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if(!(tfQrText.getText().equals(""))){
                //create() Method make the QRcode Image
                create();
            }               
        }
    });

The Error occurs on line:

BufferedImage iconBuffered = ImageIO.read(iconFile);

When I make it .jar file, it says: Opening file with windows CMD to know why it won't open

My Project structure is like this:

+src
+qrCodeGenerator
  -VisualQrCodeGenerator
  -icon.png
  -qrCodeImage.png

The code is running properly and without any error in program and I can work with it. But when I make it .jar file, it errors me as I uploaded it image.

Upvotes: 1

Views: 56

Answers (1)

Tunaki
Tunaki

Reputation: 137084

This is normal: you can't access a classpath resource as a File object. This is because it is embedded inside a JAR. It works inside your IDE because resources are typically stored inside a temporary folder (and not inside a JAR).

You need to access it with an InputStream using Class.getResourceAsStream and use ImageIO.read(InputStream) instead.

As such, change your code to:

qrBufferedImage = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("qrCodeImage.png"));

and

iconBuffered = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("icon.png"));

Upvotes: 1

Related Questions