0

I'm developing a QR generator app in java.This is the generating code,

try {

            ByteArrayOutputStream out = QRCode.from(txt_input.getText()).to(ImageType.PNG).stream();
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

            BufferedImage image = ImageIO.read(in);

            lbl_output.setIcon(null);
            lbl_output.setIcon(new ImageIcon(image));

            String pic = "image";

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, " Please enter valid text !");
        }

After generate the QR image I need to save it.So I used this code,

JFileChooser save = new JFileChooser();
int response = save.showSaveDialog(null);

            if (response == JFileChooser.APPROVE_OPTION) {
               try {
                    File fileToSave = new File(pic + ".png");
                    ImageIO.write(image, "PNG", fileToSave);

                } catch (Exception e) {

                }
             }

But there is an exception like,

java.lang.IllegalArgumentException: image == null!
    at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
    at javax.imageio.ImageIO.write(ImageIO.java:1520)
Md. Nasir Uddin Bhuiyan
  • 1,598
  • 1
  • 14
  • 24

1 Answers1

1

There's no reason to use ImageIO here, because your QRCode class already writes the image in PNG format to an array of bytes.

Instead, just copy the bytes to the file you want.

I.e.:

ByteArrayOutputStream out = QRCode.from(txt_input.getText()).to(ImageType.PNG).stream();
byte[] bytes = out.toByteArray();

...

FileChooser save = new JFileChooser();
int response = save.showSaveDialog(null);

if (response == JFileChooser.APPROVE_OPTION) {
    File fileToSave = new File(pic + ".png");

    // Try-with-resource
    try (OutputStream out = new FileOutputStream(fileToSave)) {
        out.write(bytes);
        out.flush();
    }
}
Harald K
  • 26,314
  • 7
  • 65
  • 111