2015-04-12 49 views
0

我正在開發中java.This一個QR發電機的應用是生成代碼,如何在java中保存圖像文件?

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 !"); 
     } 

生成QR像我需要保存it.So我用這個代碼後,

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) { 

       } 
      } 

但有一個例外,像,

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) 
+4

不要離開catch塊empty.use'的printStackTrace();',以確定是否發生了錯誤。 –

+0

'image'包含什麼值? – immibis

+1

@OptimasePrime'BufferedImage image = ImageIO.read(in);' - 你知道這個聲明瞭一個名爲「image」的新變量,它與任何其他變量碰巧稱爲「image」不同,對嗎? – immibis

回答

1

沒有理由在這裏使用ImageIO,因爲你的QRCode類已經寫入圖像PNG格式轉換爲字節數組。

相反,只需將字節複製到所需的文件。

即:

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(); 
    } 
}